Skip to content

Instantly share code, notes, and snippets.

@gclaramunt
Created November 15, 2011 19:21
Show Gist options
  • Save gclaramunt/1368041 to your computer and use it in GitHub Desktop.
Save gclaramunt/1368041 to your computer and use it in GitHub Desktop.
Luhn credit card verification check in a couple of lines of Scala
object LuhnCheck {
def digitToInt(x:Char)=x.toInt-'0'.toInt
def digitSeqToInt(ds:Seq[Char])= ds map digitToInt _
def double ( xs:Seq[Int]) = xs zip (0 to xs.size-1) map { xy => xy._1+xy._1*((xy._2+1) %2) }
def isValid(cc:String) = (digitSeqToInt (double ( digitSeqToInt (cc)) mkString("") ) sum) % 10 == 0
}
// or from Rosseta Stone
def luhnTest(number: String): Boolean = {
val digits = number.reverse.map { _.toString.toInt }
val s = digits.grouped(2) map { t => t(0) +
(if (t.length > 1) (t(1) * 2) % 10 + t(1) / 5 else 0)
}
s.sum % 10 == 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment