Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computing all possibilities of replacing one character by another

> 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.

like image 484
fredoverflow Avatar asked Jul 13 '12 16:07

fredoverflow


2 Answers

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 [] = [[]]
like image 199
Daniel Fischer Avatar answered Oct 04 '22 17:10

Daniel Fischer


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!","")]
like image 27
Daniel Wagner Avatar answered Oct 04 '22 16:10

Daniel Wagner