Last active
August 29, 2015 14:01
-
-
Save suminb/b4e9de281f18ae17000f to your computer and use it in GitHub Desktop.
Scala 를 배워보자 (http://www.scala-lang.org/docu/files/ScalaTutorial.pdf)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class Tree | |
case class Add(l: Tree, r: Tree) extends Tree | |
case class Sub(l: Tree, r: Tree) extends Tree | |
case class Mul(l: Tree, r: Tree) extends Tree | |
case class Square(c:Const, b: Tree, e:Const) extends Tree | |
case class Var(n: String) extends Tree | |
case class Const(v: Int) extends Tree | |
trait Comparable { | |
def < (that: Any): Boolean | |
def <=(that: Any): Boolean = (this < that) || (this == that) | |
def > (that: Any): Boolean = !(this <= that) | |
def >=(that: Any): Boolean = !(this < that) | |
} | |
object App { | |
type Environment = String => Int | |
def eval(t: Tree, env: Environment): Int = t match { | |
case Add(l, r) => eval(l, env) + eval(r, env) | |
case Sub(l, r) => eval(l, env) - eval(r, env) | |
case Mul(l, r) => eval(l, env) * eval(r, env) | |
case Square(c, b, e) => if (eval(e, env) == 1) eval(c, env) * eval(b, env) | |
else eval(b, env) * eval(Square(c, b, Const(eval(e, env) - 1)), env) | |
case Var(n) => env(n) | |
case Const(v) => v | |
} | |
def eval(t: Tree): Int = t match { | |
case Const(v) => v | |
} | |
def derivative(t: Tree, v: String): Tree = t match { | |
case Mul(l, r) => Mul(derivative(l, v), derivative(r, v)) | |
case Add(l, r) => Add(derivative(l, v), derivative(r, v)) | |
case Sub(l, r) => Sub(derivative(l, v), derivative(r, v)) | |
case Square(c, b, e) if (Var(v) == b && e != Const(1)) => Mul( | |
c, Mul(e, Square(Const(1), b, Const(eval(e) - 1)))) | |
case Square(c, b, e) => Const(1) | |
case Var(n) if (v == n) => Const(1) | |
case _ => Const(0) | |
} | |
def reduce(t: Tree): Tree = t match { | |
case Mul(l, r) if (l == Const(1)) => r | |
case Mul(l, r) if (r == Const(1)) => l | |
case Square(c, b, e) if (e == Const(1)) => Mul(c, b) | |
} | |
def main(args: Array[String]) { | |
val exp: Tree = Mul(Add(Var("x"), Var("x")), Add(Const(7), Var("y"))) | |
val env: Environment = { case "x" => 2 case "y" => 3 } | |
println("Expression: " + exp) | |
println("Evaluation with x=2, y=3: " + eval(exp, env)) | |
println("Square expression: " + eval(Square(Const(1), Const(2), Const(4)), env)) | |
println("Derivative: " + derivative(Square(Const(1), Var("x"), Const(3)), "x")) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
마음에 드는 점: