0
votes

I have the following code:

import Debug.Trace (trace)

mtrace :: Show a => String -> a -> a
mtrace msg value =
  trace (msg ++ show value) value

isVowel :: Char -> Bool
isVowel = (`elem` "AEIOU")

vowelSlice :: String -> ([Maybe Char], String)
vowelSlice "" = ([], [])
vowelSlice (c:s)
    | isVowel c = (Nothing:chars, c:vowels)
    | otherwise = (Just c:chars, vowels)
    where (chars, vowels) = vowelSlice s

stringTogether :: [Maybe Char] -> String -> String
stringTogether [] "" = ""
stringTogehter (Just c:cs) vowels = c:stringTogether cs vowels
stringTogehter (Nothing:cs) (v:vs) = v:stringTogether cs vs

process :: String -> String
process s = stringTogether (mtrace "chars: " chars) (mtrace "vowels: " cycledVowels)
    where
      (chars, vowels) = vowelSlice s
      cycledVowels = tail vowels ++ [head vowels]

main :: IO ()
main = do
    line <- getLine
    putStrLn $ process line

for testing I run my file using the runhaskell command and the I enter HELLO PEOPLE as user input once the program is running. I'm expecting the output: HELLE POEPLO or something similar since my program is meant to shift the vowels only. My program works fine until it tries to run the stringTogether method. Specifically the issue lies with the pattern matching, I have an array:

[Just 'H',Nothing,Just 'L',Just 'L',Nothing,Just ' ',Just 'P',Nothing,Nothing,Just 'P',Just 'L',Nothing]

and a pattern (Just c:cs) vowels that I expect it to match but somehow it doesn't seem to work. When I run the code and enter HELLO WORLD I receive the following error: 18:1-25: Non-exhaustive patterns in function stringTogether I logged a few things using the trace module and everything looks as expected before entering the stringTogether function

I'm probably overlooking something really obvious but I just can't get my head around why the pattern match won't work, I hope someone is able to help. Thanks in advance!

1
Hint: it is possible that one of the two lists is not empty whereas the other is.Willem Van Onsem
Here you forgot the cases where it has (Nothing:_) [].Willem Van Onsem
Yeah my editor warned me that my patterns are not exhaustive and I tried adding a general catch all pattern at the end but it would catch every function call. Also because the function stringTogether is always called with input generated from vowelSlice it shouldn't fail.MrClottom
but you make a recursive call here, so eventually the lists will get exhausted.Willem Van Onsem
When you get unexpected warnings, look for typos. That's all the problem here is.Carl

1 Answers

3
votes

The pattern match fails because of a typo, 2 separate functions were defined instead of the intended one: stringTogether and stringTogehter. The patterns were valid but the compiler failed to find them because they had mismatching names. The function technically stringTogether only had one pattern [] "" so when the list was passed it raised the 18:1-25: Non-exhaustive patterns in function stringTogether error.