我目前正在阅读《Haskell 编程》一书(到目前为止这本书绝对令人惊叹),但在练习 4.8.8 中遇到了问题。
任务是在 Haskell 中实现Luhn 算法,使用帮助函数luhnDouble :: Int -> Int
(如果结果大于 9,则将数字加倍并减去 9)和函数mod
。
实现该luhnDouble
功能没有问题,但我正在努力将它们都带入 type 的功能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
但是我不是将函数 4Int
作为参数并Bool
因此得到 a 吗?
然后我尝试对函数进行柯里化并使用lambda 表达式:
luhn :: Int -> (Int -> (Int -> Bool))
luhn = \w ->(\x ->(\y -> (\z -> ((luhnDouble w) + x + (luhnDouble y) + z mod 10))))
但是我不确定如何if
在这里引入表达式来获得一个Bool
值。
任何人都可以帮助我,并给我一个提示,我该如何解决这个问题?