Avatar of paulfioravanti

paulfioravanti's solution

to Luhn in the Elm Track

Published at Aug 10 2019 · 0 comments
Instructions
Test suite
Solution

Given a number determine whether or not it is valid per the Luhn formula.

The Luhn algorithm is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers and Canadian Social Insurance Numbers.

The task is to check if a given string is valid.

Validating a Number

Strings of length 1 or less are not valid. Spaces are allowed in the input, but they should be stripped before checking. All other non-digit characters are disallowed.

Example 1: valid credit card number

4539 1488 0343 6467

The first step of the Luhn algorithm is to double every second digit, starting from the right. We will be doubling

4_3_ 1_8_ 0_4_ 6_6_

If doubling the number results in a number greater than 9 then subtract 9 from the product. The results of our doubling:

8569 2478 0383 3437

Then sum all of the digits:

8+5+6+9+2+4+7+8+0+3+8+3+3+4+3+7 = 80

If the sum is evenly divisible by 10, then the number is valid. This number is valid!

Example 2: invalid credit card number

8273 1232 7352 0569

Double the second digits, starting from the right

7253 2262 5312 0539

Sum the digits

7+2+5+3+2+2+6+2+5+3+1+2+0+5+3+9 = 57

57 is not evenly divisible by 10, so this number is not valid.

Elm Installation

Refer to the Installing Elm page for information about installing elm.

Writing the Code

The first time you start an exercise, you'll need to ensure you have the appropriate dependencies installed. Thankfully, Elm makes that easy for you and will install dependencies when you try to run tests or build the code.

Execute the tests with:

$ elm-test

Automatically run tests again when you save changes:

$ elm-test --watch

As you work your way through the test suite, be sure to remove the skip <| calls from each test until you get them all passing!

Source

The Luhn Algorithm on Wikipedia http://en.wikipedia.org/wiki/Luhn_algorithm

Submitting Incomplete Solutions

It is possible to submit an incomplete solution so you can see how others have completed the exercise.

Tests.elm

module Tests exposing (tests)

import Expect
import Luhn exposing (valid)
import Test exposing (Test, describe, skip, test)


tests : Test
tests =
    describe "Luhn"
        [ test "single digit strings can not be valid" <|
            \_ ->
                Expect.equal False (valid "1")
        , skip <|
            test "a single zero is invalid" <|
                \_ ->
                    Expect.equal False (valid "0")
        , skip <|
            test "a simple valid SIN that remains valid if reversed" <|
                \_ ->
                    Expect.equal True (valid "059")
        , skip <|
            test "a simple valid SIN that becomes invalid if reversed" <|
                \_ ->
                    Expect.equal True (valid "59")
        , skip <|
            test "a valid Canadian SIN" <|
                \_ ->
                    Expect.equal True (valid "055 444 285")
        , skip <|
            test "invalid Canadian SIN" <|
                \_ ->
                    Expect.equal False (valid "055 444 286")
        , skip <|
            test "invalid credit card" <|
                \_ ->
                    Expect.equal False (valid "8273 1232 7352 0569")
        , skip <|
            test "valid strings with a non-digit included become invalid" <|
                \_ ->
                    Expect.equal False (valid "055a 444 285")
        , skip <|
            test "valid strings with punctuation included become invalid" <|
                \_ ->
                    Expect.equal False (valid "055-444-285")
        , skip <|
            test "valid strings with symbols included become invalid" <|
                \_ ->
                    Expect.equal False (valid "055£ 444$ 285")
        , skip <|
            test "single zero with space is invalid" <|
                \_ ->
                    Expect.equal False (valid " 0")
        , skip <|
            test "more than a single zero is valid" <|
                \_ ->
                    Expect.equal True (valid "0000 0")
        , skip <|
            test "input digit 9 is correctly converted to output digit 9" <|
                \_ ->
                    Expect.equal True (valid "091")
        ]
module Luhn exposing (valid)


valid : String -> Bool
valid input =
    let
        number =
            input
                |> String.replace " " ""
    in
    isValidFormat number && isValidValue number



-- PRIVATE


isValidFormat : String -> Bool
isValidFormat number =
    String.length number > 1 && String.all Char.isDigit number


isValidValue : String -> Bool
isValidValue number =
    let
        isEvenlyDivisibleBy10 : Int -> Bool
        isEvenlyDivisibleBy10 num =
            remainderBy 10 num == 0
    in
    number
        |> toReversedNumbers
        |> chunkEvery 2
        |> List.foldl addLuhnValue 0
        |> isEvenlyDivisibleBy10


toReversedNumbers : String -> List Int
toReversedNumbers number =
    number
        |> String.reverse
        |> String.split ""
        |> List.filterMap String.toInt


chunkEvery : Int -> List Int -> List (List Int)
chunkEvery size list =
    if size >= List.length list then
        [ list ]

    else
        let
            chunk =
                List.take size list

            tail =
                List.drop size list
        in
        chunk :: chunkEvery size tail


addLuhnValue : List Int -> Int -> Int
addLuhnValue chunk acc =
    case chunk of
        [ leftValue ] ->
            acc + leftValue

        [ leftValue, rightValue ] ->
            let
                double : Int -> Int
                double number =
                    number * 2

                subtract9IfGreaterThan9 : Int -> Int
                subtract9IfGreaterThan9 number =
                    if number > 9 then
                        number - 9

                    else
                        number

                rightLuhnValue =
                    rightValue
                        |> double
                        |> subtract9IfGreaterThan9
            in
            acc + leftValue + rightLuhnValue

        _ ->
            acc

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?