Skip to content

Instantly share code, notes, and snippets.

@suminb
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suminb/b4e9de281f18ae17000f to your computer and use it in GitHub Desktop.
Save suminb/b4e9de281f18ae17000f to your computer and use it in GitHub Desktop.
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"))
}
}
@suminb
Copy link
Author

suminb commented May 11, 2014

마음에 드는 점:

  • 자바와 연동 됨 (JVM 위에서 돌아가며, Scala 컴파일러/인터프리터 옵션도 Java 와 호환 됨)
  • 모든 객체가 first-class value (함수를 포함해서)
  • 익명 함수 지원
  • 패턴 매칭 - Haskell 만큼은 아니지만 꽤 강력한 패턴 매칭을 제공
  • Traits 라고 자바의 인터페이스와 비슷하지만 구현체를 가질 수 있는 어떤 장치를 제공

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment