alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (directInterpreter.scala)

This example Scala source code file (directInterpreter.scala) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Scala tags/keywords

add, fun, list, name, num, num, pair, string, term, term, value, value, wrong, wrong

The Scala directInterpreter.scala source code

object directInterpreter {

  type Name = String;

  trait Term;
  case class Var(x: Name) extends Term;
  case class Con(n: Int) extends Term;
  case class Add(l: Term, r: Term) extends Term;
  case class Lam(x: Name, body: Term) extends Term;
  case class App(fun: Term, arg: Term) extends Term;

  trait Value;
  case object Wrong extends Value;
  case class Num(n: Int) extends Value;
  case class Fun(f: Value => Value)extends Value;

  def showval(v: Value): String = v match {
    case Wrong => "<wrong>"
    case Num(n) => n.toString()
    case Fun(f) => "<function>"
  }

  type Environment = List[Pair[Name, Value]];

  def lookup(x: Name, e: Environment): Value = e match {
    case List() => Wrong
    case Pair(y, b) :: e1 => if (x == y) b else lookup(x, e1)
  }

  def add(a: Value, b: Value): Value = Pair(a, b) match {
    case Pair(Num(m), Num(n)) => Num(m + n)
    case _ => Wrong
  }

  def apply(a: Value, b: Value) = a match {
    case Fun(k) => k(b)
    case _ => Wrong
  }

  def interp(t: Term, e: Environment): Value = t match {
    case Var(x) => lookup(x, e)
    case Con(n) => Num(n)
    case Add(l, r) => add(interp(l, e), interp(r, e))
    case Lam(x, t) => Fun(a => interp(t, Pair(x, a) :: e))
    case App(f, t) => apply(interp(f, e), interp(t, e))
  }

  def test(t: Term): String = 
    showval(interp(t, List()));

  val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11)));

  def main(args: Array[String]) = 
    System.out.println(test(term0));
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala directInterpreter.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.