【发布时间】:2016-11-27 18:32:30
【问题描述】:
我目前正在阅读Programming in Haskell 这本书(到目前为止这绝对是惊人的),但在练习 4.8.8 中遇到了问题。
任务是在 Haskell 中实现 Luhn algorithm,使用帮助函数 luhnDouble :: Int -> Int(如果结果大于 9,则将数字加倍并减去 9)和 mod功能。
实现luhnDouble 函数没有问题,但我正在努力将它们都带入Int -> Int -> Int -> Int -> Bool 类型的函数中。
我尝试了两种方法:
luhn :: Int -> Int -> Int -> Int -> Bool
luhn w x y z = if (((luhnDouble w) + x + (luhnDouble y) + z) mod 10) == 0 then True
else False
我收到一个类型错误。
* Couldn't match expected type `(Integer -> Integer -> Integer)
-> Integer -> Integer'
with actual type `Int'
* The function `(luhnDouble w) + x + (luhnDouble y) + z'
is applied to two arguments,
but its type `Int' has none
In the first argument of `(==)', namely
`(((luhnDouble w) + x + (luhnDouble y) + z) mod 10)'
In the expression:
(((luhnDouble w) + x + (luhnDouble y) + z) mod 10) == 0
但我不是将函数 4 Ints 作为参数并因此得到 Bool 吗?
然后我尝试对函数进行柯里化并使用 lambda 表达式:
luhn :: Int -> (Int -> (Int -> Bool))
luhn = \w ->(\x ->(\y -> (\z -> ((luhnDouble w) + x + (luhnDouble y) + z mod 10))))
但我不确定如何在此处引入if 表达式以获得Bool 值作为结果。
谁能帮帮我,告诉我如何解决这个问题?
【问题讨论】:
-
您的
if表达式似乎无效。你错过了一个“其他”案例。 -
哦,是的,对不起,我忘了。我现在就加进去!
-
您使用
mod作为中缀,但没有将其包裹在反引号中,因此它被视为参数。这可能是你的错误。