1

I am looking for a way to replace occurrences of strings in Haskell. I have this working for single pairs. My current function is implemented like so:

replaceList :: (Eq a) => [a] -> ([a],[a]) -> [a]
replaceList z@(x:xs) (a,b)
| take (length a) z == a = b ++ strt z (length a)
| otherwise = x : replaceList xs (a,b)

In this context, strt is just a function that returns a list starting at a certain index. This function works. replaceList "Dragon" ("ragon","odo") will return "I am a dodo". However, I am looking for a way to make this function accept a list of these tupples. For instance:

replaceList "I am a dragon" [("I","You"),("am","are"),("a dragon","awesome")] returning "You are awesome".

The methods I have tried so far have been to map a partially applied replaceList over a list of tupples, but that returns a list of each individual element changed. I also tried using this code:

replaceInfinity :: (Eq a) => [a] -> [([a],[a])] -> [a]
replaceInfinity x [] = x
replaceInfinity x ((a,b):ys) = (flip replaceList (a,b)) . (replaceInfinity x ys) 

but that fails to compile. I'm relatively new to Haskell and am using this to rewrite an old language preprocessor. I can't understand the logic of how to implement this type of function.

Could someone tell me the tactic to get to the answer, or even implement the function for me so I could learn how it would be done? If it helps, I have the entire source file I've been using to play around with this here: http://hpaste.org/85363

1 Answer 1

1

The smallest change to your code that I could think of is:

replaceInfinity :: Eq a => [a] -> [([a], [a])] -> [a]
replaceInfinity x []     = x
replaceInfinity x (y:ys) = replaceInfinity (replaceList x y) ys

OUTPUT:
*Main> replaceInfinity "I am a dragon" [("I","You"),("am","are"),("a dragon","awesome")]
"You are awesome"


On second thought:

replaceInfinity x ((a,b):ys) = (flip replaceInfinity ys) . (replaceList x) $ (a,b)

Or more succinctly:

replaceInfinity x (y:ys) = flip replaceInfinity ys . replaceList x $ y
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks groovy. Coming from imperative languages with somewhat easier data structures and iteration, I just couldn't wrap my head around how to do it, even though I got close. I guess I kind of misunderstood composition, because replaceInfinity ( replaceList x y) ys was what I was trying to do with it.
@Dymatic I got the compositional statement to work this way: replaceInfinity x [] = x; replaceInfinity x (y:ys) = flip replaceInfinity ys . replaceList x $ y

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.