I tried my hand at coding the Luhn algorithm in Smalltalk, as almost every other language seems to have had a shot at it. I am certain that are better implementations than this quick hack, but here it is. It works true for the example case that the accordian guy uses, but having no other test cases, this is what I have. Note that this is in the Squeak dialect, and it attaches to a base class.
Integer>>isValidLuhn
| str accOdd accEven anEven |
accOdd _ accEven _ 0.
str _ ReadStream on: self asString reverse.
[str atEnd]
whileFalse: [accOdd _ accOdd + str next asString asNumber.
anEven _ str next.
anEven
ifNotNil: [anEven _ anEven asString asNumber * 2.
anEven > 9
ifTrue: [anEven _ anEven - 9].
accEven _ accEven + anEven]].
^ accOdd + accEven \ 10 = 0
[update: Whoops. I was using a stripped image (the image I use for my Comanche Swiki), so all the variable names were lost, so I replaced them. The underscore is the keyboard key used for the assignment operator, which in Squeak images renders as a left-pointing arrow. The caret sign is an up arrow and returns from the function.
update: There must be a better implementation, probably using #inject:into:. The implementation above streams through the digits of the integer, accumulating the odd and even digits alternately.
update: I don’t know why the algorithm description insists on adding the digits of the doubled even-positioned digits; it seems to me that the digit-added property holds true even if you add the doubled digits together after, instead of at each step. That is, 35 + 11 and 8 + 2 both ultimately equal one. I don’t remember what this property is called. If that is the case, the implementation above could be simplified to something like, um, oh, wait, never mind. Sequence of actions is important. Never mind.
update: I originally pasted in the file-in version, but I thought if I presented as it is presented in Kent Beck, it would be less scary. Smalltalk really is a pretty language.
update: Whoops, more Smalltalk implementations just popped into my head: here and here.]
10:06:50 PM
|
|