Sha256: 28f337b4e51a9d34e31405415140c9003e5f83c80f3e2ead6779a9ecc467e26e

Contents?: true

Size: 1 KB

Versions: 68

Compression:

Stored size: 1 KB

Contents

module Luhn exposing (valid)

import Char exposing (isDigit)
import Regex exposing (regex)
import String


valid : String -> Bool
valid input =
    let
        nonDigit =
            Regex.contains (regex "[^0-9 ]") input

        tooShort =
            String.length digits < 2

        digits =
            String.filter isDigit input
    in
    if nonDigit || tooShort then
        False
    else
        checksum digits == 0


checksum : String -> Int
checksum input =
    let
        calculate x =
            if x < 5 then
                x * 2
            else
                x * 2 - 9

        remainder x =
            x % 10
    in
    input
        |> String.reverse
        |> String.toList
        |> List.map (Result.withDefault 0 << String.toInt << String.fromChar)
        |> List.indexedMap (,)
        |> List.map
            (\( i, x ) ->
                if i % 2 == 0 then
                    x
                else
                    calculate x
            )
        |> List.sum
        |> remainder

Version data entries

68 entries across 68 versions & 1 rubygems

Version Path
trackler-2.2.1.139 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.138 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.137 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.136 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.135 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.134 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.133 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.132 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.131 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.130 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.129 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.128 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.127 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.126 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.125 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.124 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.123 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.122 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.121 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.120 tracks/elm/exercises/luhn/Luhn.example.elm