码迷,mamicode.com
首页 > 其他好文 > 详细

scala programming (1)

时间:2014-10-23 14:19:57      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   on   

ChecksumAccumulator.scala

import scala.collection.mutable.Map

class 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.calculate

object 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)

标签:style   blog   color   io   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/wzm-xu/p/4045549.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!