Last active
May 10, 2019 01:32
-
-
Save MarneeDear/5898aa3b569aacfd481042e1741c8282 to your computer and use it in GitHub Desktop.
Luhn Aglorithm in F#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// C# example on Wikipedia here https://en.wikipedia.org/wiki/Luhn_algorithm#C# | |
//Find exmaple credit card numbers here https://www.freeformatter.com/credit-card-number-generator-validator.html | |
let ccNbr = "5181789570841591" //Master Card | |
let digits = (string ccNbr).ToCharArray() |> Array.rev | |
printfn "%A" digits | |
let mutable sum = 0 | |
//let mutable n = | |
let mutable alternate = false | |
for d in digits do //i in [0 .. digits.Length - 1] do | |
let mutable tmp = int (d.ToString()) | |
printfn "%A" tmp | |
if (alternate) then | |
tmp <- tmp * 2 | |
if tmp > 9 then | |
tmp <- (tmp % 10) + 1 | |
sum <- sum + tmp | |
alternate <- not alternate | |
sum % 10 = 0 | |
//How to make this more functional? | |
//from this gist https://github.com/ChrisPritchard/My-Exercism-Solutions/blob/master/fsharp/luhn/Luhn.fs | |
open System | |
let number = "11111111" | |
if Seq.exists (fun c -> not (Char.IsNumber c || c = ' ')) number then false | |
else | |
printfn "Start check" | |
let clean = number |> Seq.filter Char.IsNumber |> Seq.map (string >> int) | |
if Seq.length clean = 1 then false | |
else | |
let multiply i n = | |
match i % 2 with | |
| 1 when n < 5 -> n * 2 | |
| 1 -> (n * 2) - 9 | |
| _ -> n | |
let sum = clean |> Seq.rev |> Seq.mapi multiply |> Seq.sum | |
sum % 10 = 0 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment