Skip to content

Instantly share code, notes, and snippets.

@miklund
Created December 27, 2015 12:53
Show Gist options
  • Save miklund/b3682e35f729b59a4235 to your computer and use it in GitHub Desktop.
Save miklund/b3682e35f729b59a4235 to your computer and use it in GitHub Desktop.
2009-07-01 LUHN validation with F#
# Title: LUHN validation with F#
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2009/07/01/luhn-validation-with-fsharp.html
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"
// 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