> magicFunction 'l' '_' "hello world"
["he_lo world", "hel_o world", "hello wor_d"]
Is there such a magic function in the standard Prelude or can it be composed easily with other functions?
And no, this isn't homework, but still, please don't spend too much time hand-rolling your own complicated solution, I'd rather do that myself than waste your time ;) Just asking if it's in the standard.
EDIT: Here is my first attempt:
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)
Can it be improved? Surely something like replace
must be in the standard? I found replace :: Eq a => a -> a -> [a] -> [a]
in Network.CGI.Protocol
, but it has the wrong signature.
No, there isn't something like magicFunction
in the standard libraries. But it's easy to write yourself, so unless it's an often-used function, there's no point putting it in a library. In addition to your version and Daniel Wagner's hint with tails
and inits
, here's a simple implementation:
magicFunction find replace = init . helper
where
helper (c:cs) = if c == find then ((replace:cs):) else id $ map (c:) (helper cs)
helper [] = [[]]
There is nothing like this in the standard distribution. However, there's a well-known trick that could form the start of a solution:
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!","")]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With