Possible Duplicate:
Iterating through a String and replacing single chars with substrings in haskell
I'm trying to implement a function that looks at a String ([Chars]) and checks for every letter whether this letter should be replaced with another string. For example we might have a [Chars] consisting of "XYF" and rules that says "X = HYHY", "Y = OO", then our output should become "HYHYOOF".
I want to use the following two types which I have defined:
type Letters = [Char]
data Rule = Rule Char Letters deriving Show
My idea is that the function should look something like the following below using guards. The problem is however I can't find any information on how to the recursive call should look like when i want browse through all my rules to see if any of them fits to the current letter x. I hope anyone can give some hints on how the notation goes.
apply :: Letters -> [Rule] -> Letters
apply _ _ = []
apply (x:xs) (Rule t r:rs)
| x /= t = apply x (Rule t rs)
| x == t = r++rs:x
| otherwise =
I would suggest a helper function to check whether a rule matches,
matches :: Char -> Rule -> Bool
matches c (Rule x _) = c == x
and then you check for each character whether there are any matching rules
apply :: Letters -> [Rule] -> Letters
apply [] _ = []
apply s [] = s
apply (c:cs) rules = case filter (matches c) rules of
[] -> c : apply cs rules
(Rule _ rs : _) -> rs ++ apply cs rules
If you try an explicit recursion on rules
within apply
, it will become too ugly, since you need to remember the full rules list for replacing later characters.