首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Luhn算法的实现

Luhn算法的实现
EN

Stack Overflow用户
提问于 2015-07-01 20:59:13
回答 1查看 1.3K关注 0票数 1

我期待luhn 5594589764218858 = True,但它总是False

代码语言:javascript
复制
-- 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逆转了这个数字,但我认为它无论如何都会起作用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-01 23:03:32

代码片段x `div` 10 == 0并不是x是否可除以10的正确检查;您应该使用`mod`。此外,这一方程式是不正确的:

代码语言:javascript
复制
sumDigits (x : [])    = x

(尝试,例如sumDigits [10].)它可以修复,但删除它更简单,仍然是正确的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31171567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档