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.159 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.158 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.157 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.156 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.155 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.154 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.153 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.152 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.151 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.150 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.149 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.148 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.147 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.146 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.145 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.144 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.143 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.142 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.141 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.140 tracks/elm/exercises/luhn/Luhn.example.elm