【问题标题】:Luhn function in HaskellHaskell 中的 Luhn 函数
【发布时间】:2016-11-27 18:32:30
【问题描述】:

我目前正在阅读Programming in Haskell 这本书(到目前为止这绝对是惊人的),但在练习 4.8.8 中遇到了问题。

任务是在 Haskell 中实现 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

但我不是将函数 4 Ints 作为参数并因此得到 Bool 吗?

然后我尝试对函数进行柯里化并使用 lambda 表达式

luhn :: Int -> (Int -> (Int -> Bool))
luhn = \w ->(\x ->(\y -> (\z -> ((luhnDouble w) + x + (luhnDouble y) + z mod 10))))

但我不确定如何在此处引入if 表达式以获得Bool 值作为结果。

谁能帮帮我,告诉我如何解决这个问题?

【问题讨论】:

  • 您的if 表达式似乎无效。你错过了一个“其他”案例。
  • 哦,是的,对不起,我忘了。我现在就加进去!
  • 您使用mod 作为中缀,但没有将其包裹在反引号中,因此它被视为参数。这可能是你的错误。

标签: haskell luhn


【解决方案1】:
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

【讨论】:

  • 我添加了一个编辑。抱歉,如果它与您的意图相冲突。
【解决方案2】:
luhn :: Int -> Int -> Int -> Int -> Bool
luhn w x y z = (luhnDouble w + x + luhnDouble y + z) `mod` 10 == 0

这会起作用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 2020-02-19
    相关资源
    最近更新 更多