我期待luhn 5594589764218858 = True,但它总是False
-- Get the last digit from a number
lastDigit :: Integer -> Integer
lastDigit 0 = 0
lastDigit n = mod n 10
-- Drop the last digit from a number
dropLastDigit :: Integer -> Integer
dropLastDigit n = div n 10
toRevDigits :: Integer -> [Integer]
toRevDigits n
| n <= 0 = []
| otherwise = lastDigit n : toRevDigits (dropLastDigit n)
-- Double every second number in a list starting on the left.
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther [] = []
doubleEveryOther (x : []) = [x]
doubleEveryOther (x : y : z) = x : (y * 2) : doubleEveryOther z
-- Calculate the sum of all the digits in every Integer.
sumDigits :: [Integer] -> Integer
sumDigits [] = 0
sumDigits (x : []) = x
sumDigits (x : y) = (lastDigit x) + (dropLastDigit x) + sumDigits y
-- Validate a credit card number using the above functions.
luhn :: Integer -> Bool
luhn n
| sumDigits (doubleEveryOther (toRevDigits n)) `div` 10 == 0 = True
| otherwise = False我知道这件事可以做得更容易,但我正在跟踪一个Haskell 介绍性。我认为我唯一的问题是luhn函数。本课程提到的问题可能会发生,因为toRevDigits逆转了这个数字,但我认为它无论如何都会起作用。
发布于 2015-07-01 23:03:32
代码片段x `div` 10 == 0并不是x是否可除以10的正确检查;您应该使用`mod`。此外,这一方程式是不正确的:
sumDigits (x : []) = x(尝试,例如sumDigits [10].)它可以修复,但删除它更简单,仍然是正确的。
https://stackoverflow.com/questions/31171567
复制相似问题