jiacai2050 / ideas

Think more
https://github.com/jiacai2050/ideas/issues
29 stars 2 forks source link

scala tutorials #29

Open jiacai2050 opened 8 years ago

jiacai2050 commented 8 years ago

calc.scala

abstract class Tree
case class Sum(l: Tree, r: Tree) extends Tree
case class Val(n: String) extends Tree
case class Const(v: Int) extends Tree

type Environment = String => Int

def eval(t: Tree, env: Environment):Int = t match {
    case Sum(l, r) => eval(l, env) + eval(r, env)
    case Val(n)    => env(n)
    case Const(v)  => v
}

val exp = Sum(Val("x"), Sum(Val("y"), Const(4)))
println("x + (y + 4) = " + eval(exp, {case "x" => 1 case "y" => 2}))

Timer.scala

object Timer {
    def oncePerSecond(cb: () => Unit) = {
        while (true) {
            cb()
            Thread sleep 1000
        }

    }
    def main(arg: Array[String]) = {
        oncePerSecond(() => {
            println("time flies...")
        })
    }
}

参考:

jiacai2050 commented 8 years ago

Scala 之父谈