Created
December 27, 2015 12:53
-
-
Save miklund/b3682e35f729b59a4235 to your computer and use it in GitHub Desktop.
2009-07-01 LUHN validation with F#
This file contains hidden or 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
# Title: LUHN validation with F# | |
# Author: Mikael Lundin | |
# Link: http://blog.mikaellundin.name/2009/07/01/luhn-validation-with-fsharp.html |
This file contains hidden or 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
let pid = [6; 9; 0; 1; 0; 1; 1; 2; 3; 6] | |
if luhn10 pid then | |
printfn "Your personal identity number is valid" | |
else | |
printfn "Your personal identity number is invalid" |
This file contains hidden or 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
// Product may be 1 or 2, largest possible double is 18 | |
// If result of product is greater than 9 add the parts of | |
// the product together. | |
// Example 9 * 2 = 18 => 1 + 8 = 9 | |
// Example 6 * 2 = 12 => 1 + 2 = 3 | |
let calculateProduct x product = | |
let double = x * product | |
match double with | |
| double when (double > 9) -> 1 + (double - 10) | |
| double -> double | |
// 2, 1, 2, 1, 2, 1, 2, 1.... | |
let indexProduct x = ((x + 1) % 2) + 1 | |
// For each and every number in pidList add result of calcAtom | |
let rec luhnAlgorithm numberList index = | |
match numberList with | |
| head :: tail -> calculateProduct head (indexProduct index) + luhnAlgorithm tail (index + 1) | |
| [] -> 0 | |
// PID is valid if the result from luhnAlgorithm divides evenly with 10 | |
let luhn10 pid = ((luhnAlgorithm pid 0) % 10) = 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment