Calculating the EAN Check Digit in Erlang

EAN and UPC codes come with a Check Digit in the end. A tool for EAN Check Digit calculation (called EANcalc) was the first program I ever sold. It was written in GW-Basic and I sold it for 30 DM (15 U$). I was 12 or so.

Since then I have implemented EAN Check digits in many Languages. Now in Erlang:

% @doc calculate a EAN check digit
ean_digit(Nums) ->
    {_, Summe} =
    lists:foldr(fun(X, {Factor, Summe}) ->
                    {4-Factor, Summe + ((X-$0) * Factor)}
                end, {3, 0}, Nums),
    [$0 + ((10-(Summe rem 10)) rem 10)].

make_ean(Num) ->
    Prefix = "4005998",
    EanRaw = Prefix ++ Num),
    EanRaw ++ ean_digit(EanRaw).

[$2] = ean_digit("400599871650")
"4005998716502" = make_ean("71650")

Leave a Reply