Give a char if a letter exists in a string

I'm currently having trouble doing a letterCheck function which gives me a string of numbers given two Strings. My code is below:

letterCheck :: String -> String -> String
letterCheck _ [] = []
letterCheck (w:ws) (y:ys)
 | w == y = '3' : letterCheck ws ys
 | w `elem` (y:ys) = '7' : letterCheck ws ys
 | otherwise = '9' : letterCheck ws ys

For reference the conditions I want are:

If letter in string 1 is the same as a letter in string 2, give '3';
If letter in string 1 exists in string 2 but is not the same, give '7';
Otherwise if a letter in string 1 isn't in string 2 at all, give '9';


The second guard in the code will not work because the second string being referenced decrements until no elements that exist in the full string are there for comparison. How can I fix this?

Upvotes: 0

Views: 119

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 153132

If you want access to the whole string, you have to pass a copy of the whole string that doesn't get destructured. You can hide this implementation detail using a where block:

letterCheck ws ys = go ws ys ys where
    go _ [] _ = []
    go (w:ws) (y:ys) ysAll
        | w `elem` ysAll = '7' : letterCheck ws ys ysAll

Upvotes: 4

Related Questions