2016-11-27 56 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