我目前正在阅读“Haskell程序设计”一书(到目前为止,这本书绝对令人惊讶),但在练习4.8.8中遇到了一个问题。
任务是在Haskell中实现https://en.wikipedia.org/wiki/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但是,我不是将函数4Int作为参数并因此获得一个Bool吗?
然后,我尝试运行函数并使用lambda表达式。
luhn :: Int -> (Int -> (Int -> Bool))
luhn = \w ->(\x ->(\y -> (\z -> ((luhnDouble w) + x + (luhnDouble y) + z mod 10))))但是,我不知道如何在这里引入if表达式,从而得到一个Bool值。
有人能帮我一下吗,告诉我怎么解决这个问题?
发布于 2016-11-27 18:41:51
luhn :: Int -> Int -> Int -> Int -> Bool
luhn w x y z = if (((luhnDouble w) + x + (luhnDouble y) + z) mod 10) == 0 then Trueelse之后的if。mod,而不是infix `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发布于 2020-02-13 00:58:16
luhn :: Int -> Int -> Int -> Int -> Bool
luhn w x y z = (luhnDouble w + x + luhnDouble y + z) `mod` 10 == 0这会起作用的
https://stackoverflow.com/questions/40832422
复制相似问题