haskellpattern-matchingnon-exhaustive-patternsguard-clause

"Non-exhaustive patterns in function" error when appending value before function call


I'm not sure what I'm not handling. Suppose I have a function, that converts an integer to a string. Call it converter.

Now, to convert position integer to string, I just call converter. To convert a negative integer to string, I append - to the converter call.

This is my code:

converter :: Integer -> String
converter x
    | x == 0 = "0"
    | x == 1 = "1"
    | x == 2 = "2"
    | x == 3 = "3"
    | x == 4 = "4"
    | x == 5 = "5"
    | x == 6 = "6"
    | x == 7 = "7"
    | x == 8 = "8"
    | x == 9 = "9"
    | x > 9 = z
    where
    (a, b) = divMod x 10
    z = (converter a) ++ (converter b)

negOrPosConverter :: NegOrPosInteger -> String
negOrPosConverter (ActualInt x)
    | x >= 0 = converter x
    | x < 0 = "-" ++ (converter x)

When I run the code and try negOrPosConverter (ActualInt (-200)) I get this error:

"-*** Exception: theConverter.hs:(19,1)-(27,32): Non-exhaustive patterns in function converter

Any idea why?


Solution

  • The problem is that converter is only defined for nonnegative numbers. You prepend a "-" when it's negative, but you forgot to invert the actual number you pass to it. Try this instead:

    negOrPosConverter :: NegOrPosInteger -> String
    negOrPosConverter (ActualInt x)
        | x >= 0 = converter x
        | x < 0 = '-' : converter (-x)
    

    Note converter (-x) instead of converter x.


    Also, if this isn't just for practice, note that the show function already exists in Prelude to convert numbers (and lots of other things too) into strings.