我目前正在阅读这本书 Programming in Haskell (到目前为止这绝对是惊人的),但在练习 4.8.8 中遇到了问题。
任务是实现 Luhn algorithm 在 Haskell 中,使用帮助函数 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 个 Int
作为参数并得到一个 Bool
作为结果吗?
然后我尝试柯里化(Currying)函数并使用lambda 表达式:
luhn :: Int -> (Int -> (Int -> Bool))
luhn = \w ->(\x ->(\y -> (\z -> ((luhnDouble w) + x + (luhnDouble y) + z mod 10))))
但我不确定如何在此处引入 if
表达式以获得 Bool
值作为结果。
谁能帮我解决这个问题,并告诉我如何解决这个问题?
最佳答案
luhn :: Int -> Int -> Int -> Int -> Bool
luhn w x y z = if (((luhnDouble w) + x + (luhnDouble y) + z) mod 10) == 0 then True
- 你没有在
if
之后给它一个else
。 - 您调用的是前缀
mod
,而不是中缀`mod`
。
修复:
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
或
luhn :: Int -> Int -> Int -> Int -> Bool
luhn w x y z = if (mod ((luhnDouble w) + x + (luhnDouble y) + z) 10) == 0
then True
else False
或者,一个不那么冗余的版本:
luhn :: Int -> Int -> Int -> Int -> Bool
luhn w x y z = (mod ((luhnDouble w) + x + (luhnDouble y) + z) 10) == 0
关于haskell - Haskell 中的 Luhn 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40832422/