4

我目前正在阅读《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值。

任何人都可以帮助我,并给我一个提示,我该如何解决这个问题?

4

2 回答 2

3
luhn :: Int -> Int -> Int -> Int -> Bool
luhn w x y z = if (((luhnDouble w) + x + (luhnDouble y) + z) mod 10) == 0 then True
  1. 你没有给它一个elseafter if
  2. 您正在调用 prefix 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
于 2016-11-27T18:41:51.600 回答
1
luhn :: Int -> Int -> Int -> Int -> Bool
luhn w x y z = (luhnDouble w + x + luhnDouble y + z) `mod` 10 == 0

这将起作用

于 2020-02-13T00:58:16.423 回答