我是 Scala 新手。我尝试了土耳其公民号码验证算法。
如何实现和优化这个 scala 代码?
您可以通过此链接找到我的 java 版本https://gist.github.com/hasanozgan/5601623
trait TurkishCitizenshipNumberValidator {
private def odd(tckn: String): Int = {
tckn.zipWithIndex.foldLeft(0) {
(total, x) =>
x match {
case i if ((i._2 % 2 == 0 && i._2 < 10)) => ((i._1.asDigit) + total)
case _ => total
}
}
}
private def even(tckn: String): Int = {
tckn.zipWithIndex.foldLeft(0) {
(total, x) =>
x match {
case i if ((i._2 % 2 == 1) && i._2 < 9) => ((i._1.asDigit) + total)
case _ => total
}
}
}
private def total(tckn: String): Int = {
tckn.zipWithIndex.foldLeft(0) {
(total, x) =>
x match {
case i if (i._2 < 10) => ((i._1.asDigit) + total)
case _ => total
}
}
}
def turkishCitizenshipNumberValidator(t: String): Boolean = {
val digit10 = total(t) % 10
val digit9 = ((odd(t) * 7) - even(t)) % 10
((t(9).asDigit == digit9) && t(10).asDigit == digit10)
}
}
object test extends TurkishCitizenshipNumberValidator {
// http://tckimliknouretici.appspot.com/
turkishCitizenshipNumberValidator("29419391592")
//> res0: Boolean = true
}