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

Scala example source code file (gadts.scala)

This example Scala source code file (gadts.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

application, if, int, iszero, iszero, lit, lit, succ, succ, t, term, term

The Scala gadts.scala source code

package examples

object gadts extends Application {

  abstract class Term[T]
  case class Lit(x: Int) extends Term[Int]
  case class Succ(t: Term[Int]) extends Term[Int]
  case class IsZero(t: Term[Int]) extends Term[Boolean]
  case class If[T](c: Term[Boolean],
                   t1: Term[T],
                   t2: Term[T]) extends Term[T]

  def eval[T](t: Term[T]): T = t match {
    case Lit(n)        => n
    case Succ(u)       => eval(u) + 1
    case IsZero(u)     => eval(u) == 0
    case If(c, u1, u2) => eval(if (eval(c)) u1 else u2)
  }
  println(
    eval(If(IsZero(Lit(1)), Lit(41), Succ(Lit(41)))))
}

Other Scala examples (source code examples)

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

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

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 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.