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

use*_*875 1 haskell pattern-matching guard-clause non-exhaustive-patterns

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

现在,要将位置整数转换为字符串,我只需调用converter。要将负整数转换为字符串,请附加-converter调用中。

这是我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

当我运行代码并尝试出现negOrPosConverter (ActualInt (-200))此错误时:

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

知道为什么吗?

Jos*_*ica 6

问题是converter仅为非负数定义。"-"当它为负数时,您可以在前面加上a ,但是却忘记了将传递给它的实际数字取反。尝试以下方法:

negOrPosConverter :: NegOrPosInteger -> String
negOrPosConverter (ActualInt x)
    | x >= 0 = converter x
    | x < 0 = '-' : converter (-x)
Run Code Online (Sandbox Code Playgroud)

请注意,converter (-x)而不是converter x


另外,如果这不仅是为了练习,请注意showPrelude中已经存在该函数,可以将数字(以及许多其他东西)转换为字符串。

  • @ user2719875它只是将x传递给转换器。问题是,在这种情况下,`x'为负数,而'converter'对负数不起作用。 (2认同)