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.180 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.179 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.178 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.177 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.176 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.175 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.174 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.173 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.172 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.171 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.170 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.169 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.167 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.166 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.165 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.164 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.163 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.162 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.161 tracks/elm/exercises/luhn/Luhn.example.elm
trackler-2.2.1.160 tracks/elm/exercises/luhn/Luhn.example.elm