首页 > 代码库 > scala programming (1)
scala programming (1)
ChecksumAccumulator.scala
import scala.collection.mutable.Mapclass ChecksumAccumulator { private var sum = 0 def add(b: Byte) { sum += b } def checksum(): Int = ~(sum & 0xFF) + 1}object ChecksumAccumulator { private val cache = Map[String, Int]() def calculate(s: String): Int = if (cache.contains(s)) cache(s) else { val acc = new ChecksumAccumulator for (c <- s) acc.add(c.toByte) val cs = acc.checksum() cache += (s -> cs) cs }}
Summer.scala
import ChecksumAccumulator.calculateobject Summer { def main(args: Array[String]) { for (arg <- args) println(arg +": "+ calculate(arg)) }}
$ scalac Summer.scala ChecksumAccumulator.scala
$ scala Summer of love
Program output:
of: -213
love: -182
scala programming (1)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。