Skip to content

Instantly share code, notes, and snippets.

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)
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)
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