Skip to content

Instantly share code, notes, and snippets.

@pragdave
Created June 21, 2013 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pragdave/5833805 to your computer and use it in GitHub Desktop.
Save pragdave/5833805 to your computer and use it in GitHub Desktop.
defmodule CheckDigit do
import Enum
@doc """
Determine if a sequence of digits is valid, assuming the last digit is
a Luhn checksum. (http://en.wikipedia.org/wiki/Luhn_algorithm)
"""
def valid?(numbers) when is_list(numbers) do
numbers
|> reverse
|> map(&1 - ?0)
|> sum
|> rem(10) == 0
end
defp sum(digits), do: _sum(digits, 0)
defp _sum([], acc), do: acc
defp _sum([odd], acc), do: acc + odd
defp _sum([odd, even | tail], acc) do
even = even * 2
if even >= 10 do
even = even - 10 + 1
end
sum(tail) + odd + even
end
end
IO.puts CheckDigit.valid? '79927398713'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment