【发布时间】:2019-10-11 13:37:54
【问题描述】:
我不确定我没有处理什么。假设我有一个函数,它将整数转换为字符串。叫它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)
当我运行代码并尝试 negOrPosConverter (ActualInt (-200)) 时,我收到此错误:
"-*** Exception: theConverter.hs:(19,1)-(27,32): Non-exhaustive patterns in function converter
知道为什么吗?
【问题讨论】:
-
旁注:可以将
converter的主体替换为if ((0<=x) && (x<10)) then show x else z。show是主库中的一个有用函数,可以将大多数非字符串值转换为字符串。 -
记得开启警告,以便在编译时发现这些问题。如果你有一个警卫名单
| condition = something | condition2 = something | ...,最后一个应该是... | otherwise = something,以确保抓住所有剩余的案件。
标签: haskell pattern-matching non-exhaustive-patterns guard-clause