Skip to content

Instantly share code, notes, and snippets.

@prashcr
Created May 6, 2016 05:04
Show Gist options
  • Save prashcr/624154d92532049bcd6a77530853a928 to your computer and use it in GitHub Desktop.
Save prashcr/624154d92532049bcd6a77530853a928 to your computer and use it in GitHub Desktop.
Luhn's algorithm to validate credit card numbers
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