Thursday, 6 November 2008

Luhn's algorithm in Scheme

I came across Luhn's algorithm yesterday whilst trying to resolve a work related issue and was surprised to find an implementation in Scheme for it on Andrew Dashin's blog.

Looking at Andrew's implementation, it struck me as being a not very scheme-like implementation because it used an iterator (do) and mutating variables (set!). This gave me an opportunity to test my new found Scheme skills :-

(define (luhn-check account-number)
(letrec (
(digit (lambda (str pos) (string->number (string (string-ref str pos)))))
(add-digits (lambda (str)
(+ (digit str 0) (if (> (string-length str) 1)(digit str 1) 0))
(luhn-pair (lambda (x)
(+ (digit account-number x)
(if (> x 0) (add-digits (number->string (* (digit account-number (- x 1)) 2))) 0)
(if (> x 1) (luhn-pair (- x 2)) 0))
(luhn-pair (- (string-length account-number) 1))

It takes a string and returns a number which should be a multiple of 10 for a valid mod 10 check or a multiple of 11 for a valid mod 11 check.

No comments:

Post a Comment