【问题标题】:Computing all possibilities of replacing one character by another计算将一个字符替换为另一个字符的所有可能性
【发布时间】:2012-07-13 13:10:41
【问题描述】:
> magicFunction 'l' '_' "hello world"
["he_lo world", "hel_o world", "hello wor_d"]

标准Prelude中是否有这么神奇的功能,还是可以轻松与其他功能组合?

不,这不是家庭作业,但是,请不要花太多时间手动编写您自己的复杂解决方案,我宁愿自己做也不愿浪费您的时间 ;) 只是询问它是否在标准。


编辑:这是我的第一次尝试:

import Data.List (findIndices)

replace i y xs = take i xs ++ y : drop (i+1) xs

magicFunction x y xs = map (\i -> replace i y xs) (findIndices (== x) xs)

可以改进吗?肯定像replace 这样的东西必须在标准中吗?我在Network.CGI.Protocol 中找到了replace :: Eq a => a -> a -> [a] -> [a],但它的签名错误。

【问题讨论】:

  • 您是否要绕过脏话过滤器? XD
  • replace 的签名有什么问题?将a ~ Char 设置为[a] ~ String,我们有Eq Char,那么有什么问题?
  • @dave4420 第一个问题是它位于Network.CGI.Protocol... 作为此类功能的导入非常随机(您可以在更合适的位置找到)
  • @Norla 好吧,如果你这么想念它,你为什么不简单
  • @FredOverflow 啊,你想要一个magicFunction :: a -> a -> [a] -> [[a]] :-) 是的,你可以做得更好,你只需要遍历列表一次(你当前的尝试遍历列表一次以获得列表索引,然后为每个索引一次)。尝试使用foldr 编写它。

标签: string list haskell replace char


【解决方案1】:

标准发行版中没有这样的东西。但是,有一个众所周知的技巧可以作为解决方案的开始:

Prelude Data.List> (\xs -> zip (inits xs) (tails xs)) "Hello, world!"
[("","Hello, world!"),("H","ello, world!"),("He","llo, world!"),("Hel","lo, world!"),("Hell","o, world!"),("Hello",", world!"),("Hello,"," world!"),("Hello, ","world!"),("Hello, w","orld!"),("Hello, wo","rld!"),("Hello, wor","ld!"),("Hello, worl","d!"),("Hello, world","!"),("Hello, world!","")]

【讨论】:

    【解决方案2】:

    不,标准库中没有像 magicFunction 这样的东西。但是自己写很容易,所以除非它是一个经常使用的函数,否则将它放在库中是没有意义的。除了您的版本和 Daniel Wagner 对tailsinits 的提示之外,还有一个简单的实现:

    magicFunction find replace = init . helper
      where
        helper (c:cs) = if c == find then ((replace:cs):) else id $ map (c:) (helper cs)
        helper [] = [[]]
    

    【讨论】:

      猜你喜欢
      • 2010-12-09
      • 2012-07-16
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      • 2017-01-04
      • 2021-06-15
      • 1970-01-01
      相关资源
      最近更新 更多