计算用一个字符替换另一个字符的所有可能性

fre*_*low 6 string haskell replace list char

> magicFunction 'l' '_' "hello world"
["he_lo world", "hel_o world", "hello wor_d"]
Run Code Online (Sandbox Code Playgroud)

标准前奏中是否有这样一个神奇的功能,还是可以与其他功能轻松组合?

不,这不是家庭作业,但是,请不要花费太多时间来处理自己复杂的解决方案,我宁愿自己做也不要浪费你的时间;)只是问它是否符合标准.


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

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)
Run Code Online (Sandbox Code Playgroud)

可以改进吗?当然replace必须有标准的东西吗?我找到replace :: Eq a => a -> a -> [a] -> [a]Network.CGI.Protocol,但签名错了.

Dan*_*her 2

magicFunction不,标准库中没有类似的东西。但自己编写很容易,因此除非它是经常使用的函数,否则将其放入库中是没有意义的。除了您的版本和 Daniel Wagner 对tails和 的提示之外inits,这里还有一个简单的实现:

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