Computing all the possibilities of replacing one character with another

> magicFunction 'l' '_' "hello world" ["he_lo world", "hel_o world", "hello wor_d"] 

Is there such a magical function in the standard prelude, or can it be easily combined with other functions?

And no, this is not homework, but still, please do not spend too much time shifting your own difficult decision, I would rather do it myself than spend time;) Just asking, standard.


EDIT: Here is my first attempt:

 import Data.List (findIndices) replace iy xs = take i xs ++ y : drop (i+1) xs magicFunction xy xs = map (\i -> replace iy xs) (findIndices (== x) xs) 

Is it possible to improve? Is something like replace supposed to be in the standard? I found replace :: Eq a => a -> a -> [a] -> [a] in Network.CGI.Protocol , but it has the wrong signature.

+6
source share
2 answers

No, standard libraries do not have this type of magicFunction . But it’s easy to write to yourself, therefore, if this is not a frequently used function, it makes no sense to put it in a library. In addition to your version, and Daniel Wagner hints at 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 [] = [[]] 
+2
source

There is nothing like that in the standard distribution. However, there is a well-known trick that could be the beginning 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!","")] 
+1
source

Source: https://habr.com/ru/post/920437/


All Articles