2016-11-27 46 views
2

我目前正在通过Programming in Haskell(迄今为止绝对令人惊叹)的书,但在练习4.8.8中遇到了一个问题。Haskell中的Luhn函数

的任务是实现在Haskell的Luhn algorithm,使用帮助功能luhnDouble :: Int -> Int(双打一个数字减去9如果结果大于9)和mod funcion。

执行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 S作为参数,并得到一个Bool结果?

我又试图讨好的功能和使用lambda表达式

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

但我不知道如何把在if表达在这里获得Bool值作为结果。

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

+0

而且你'if'表达似乎无效。你错过了一个“其他”案例。 – Carcigenicate

+0

噢,对不起,我忘了。我现在将它添加进去! – TheCoolFrood

+3

而你使用'mod'作为中缀,但是没有用反引号包裹它,所以它被当作参数来对待。这可能是你的错误。 – Carcigenicate

回答

2
luhn :: Int -> Int -> Int -> Int -> Bool 
luhn w x y z = if (((luhnDouble w) + x + (luhnDouble y) + z) mod 10) == 0 then True 
  1. 你没有给它ifelse
  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 
+0

我添加了一个编辑。对不起,如果它与你的意图相冲突。 – Carcigenicate