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
import scala.language.implicitConversions | |
// R is derived from Rational with some fixes. | |
// https://sites.google.com/site/scalajp/home/documentation/scala-by-example/chapter6 | |
case class R(numer: Int, denom: Int) extends Ordered[R] { | |
def reduce: R = { | |
def gcd(x: Int, y: Int): Int = { | |
if (x == 0) y | |
else if (x < 0) gcd(-x, y) |
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
import scala.language.implicitConversions | |
sealed trait Expr { | |
def +(that: Expr): Expr = Add(List(this, that)) | |
def *(that: Expr): Expr = Mul(List(this, that)) | |
def +(that: Int ): Expr = this + N( that) | |
def -(that: Int ): Expr = this + N(-that) | |
def *(that: Int ): Expr = this * N( that) |
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
def rpn(str: String): Int = rpnPrime(str.split(' ').toList, Nil) | |
def rpnPrime(str: List[String], stack: List[Int]): Int = (str, stack) match { | |
case ("+"::t, y::x::zs) => rpnPrime(t, (x + y) :: zs) | |
case ("-"::t, y::x::zs) => rpnPrime(t, (x - y) :: zs) | |
case ("*"::t, y::x::zs) => rpnPrime(t, (x * y) :: zs) | |
case ("/"::t, y::x::zs) => rpnPrime(t, (x / y) :: zs) | |
case ("%"::t, y::x::zs) => rpnPrime(t, (x % y) :: zs) | |
case ( n::t, zs) => rpnPrime(t, (n.toInt) :: zs) | |
case _ => stack.head |
OlderNewer