haskell - Haskell 中的 Luhn 函数

标签 haskell luhn

我目前正在阅读这本书 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
  1. 你没有在 if 之后给它一个 else
  2. 您调用的是前缀 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/

相关文章:

c - Luhn算法有时有效有时失败

python - 卢恩斯算法

haskell - Data.Vector.Mixed 的用途

haskell - 提取嵌套 Exception monad 转换器的左值

PHP 客户端 PIN 安全

c - 下面的函数对给定的卡号执行 Luhn 算法,但会引发某些卡号的运行时错误。试图理解为什么?

java - IMEI 未通过 Luhn 校验和

haskell - Haskell中花括号的用途是什么?

类似于 Haskells 循环的 Ruby 方法

haskell - 有没有办法在 Haskell 中模拟线性类型?