Created
May 6, 2016 05:04
-
-
Save prashcr/624154d92532049bcd6a77530853a928 to your computer and use it in GitHub Desktop.
Luhn's algorithm to validate credit card numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Luhn do | |
def validate(num) do | |
digits = Integer.digits(num) | |
len = length digits | |
digits | |
|> Stream.with_index | |
|> Enum.reverse | |
|> Enum.reduce(0, fn {digit, index}, acc -> | |
if rem(len - index, 2) == 0 do | |
acc + (digit * 2 |> Integer.digits |> Enum.sum) | |
else | |
acc + digit | |
end | |
end) | |
|> rem(10) | |
|> Kernel.==(0) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment