[Haskell-beginners] Simplified Luhn Algorithm

mrx patrik.mrx at gmail.com
Sun Dec 31 08:49:12 UTC 2017

I guess your issue is how to represent the card numbers of arbitrary
length, or? Wouldn't a list work?


Den 31 dec 2017 05:03 skrev "trent shipley" <trent.shipley at gmail.com>:

I have the following, and it works, but I am trying teach myself Haskell,
and I have the suspicion that my solutions is both inefficient and
graceless. Any feedback would be appreciated.



8.The Luhn algorithm is used to check bank card numbers for simple errors
such as mistyping a digit, and proceeds as follows:

* consider each digit as a separate number;
* moving left, double every other number from the second last;
* subtract 9 from each number that is now greater than 9;
* add all the resulting numbers together;
* if the total is divisible by 10, the card number is valid.

Define a function luhnDouble :: Int -> Int that doubles a digit
and subtracts 9 if the result is greater than 9.

For example:

> luhnDouble 3

> luhnDouble 6

Using luhnDouble and the integer remainder function mod, define a function
luhn :: Int -> Int -> Int -> Int -> Bool
that decides if a four-digit bank card number is valid.

For example:
> luhn 1 7 8 4

> luhn 4 7 8 3

In the exercises for chapter 7 we will consider a more general version of
this function that accepts card numbers of any length.

Hutton, Graham. Programming in Haskell (pp. 45-46). Cambridge University
Press. Kindle Edition.

luhnDouble :: Int -> Int
luhnDouble x = if (2 * x) > 9
    then (2 * x) - 9
    else 2 * x

luhn :: Int -> Int -> Int -> Int -> Bool
luhn x1 x2 x3 x4 = if 0 == sum[luhnDouble x1, x2, luhnDouble x3, x4] `mod`
    then True
    else False

Beginners mailing list
Beginners at haskell.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20171231/d4800ed1/attachment.html>

More information about the Beginners mailing list