> 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
之类的东西必须符合标准吗?我在replace :: Eq a => a -> a -> [a] -> [a]
中找到Network.CGI.Protocol
,但签名错误。
答案 0 :(得分: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 [] = [[]]
答案 1 :(得分: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!","")]