Skip to content

Instantly share code, notes, and snippets.

@rhodey rhodey/Heretic.scala
Created Apr 14, 2017

Embed
What would you like to do?
True heretics keep their own time.
package org.anhonesteffort.heretic
import scala.language.implicitConversions
object Heretic {
sealed trait Ticable {
def asTics(): Long
}
sealed trait Unit extends Ticable {
def name(): String
def namePural(): String = name() + "s"
override def toString: String = name()
}
case object Tic extends Unit {
override def name(): String = "tic"
override def asTics(): Long = 1l
}
class Quantity(unit: Unit, count: Long) extends Ticable {
override def asTics(): Long = unit.asTics() * count
def +(that: Quantity): Quantity = new Quantity(Tic, this.asTics() + that.asTics())
def -(that: Quantity): Quantity = new Quantity(Tic, this.asTics() - that.asTics())
def *(that: Quantity): Quantity = new Quantity(Tic, this.asTics() * that.asTics())
def /(that: Quantity): Quantity = new Quantity(Tic, this.asTics() / that.asTics())
def ==(that: Quantity): Boolean = this.asTics() == that.asTics()
override def toString: String = {
if (count == 1) {
s"$count ${unit.name()}"
} else {
s"$count ${unit.namePural()}"
}
}
}
class Count(count: Long) {
def of(unit: Unit): Quantity = new Quantity(unit, count)
}
case object CockroachSighting extends Unit {
override def name(): String = "cockroach sighting"
override def asTics(): Long = 2l
}
case object AllergyAttack extends Unit {
override def name(): String = "allergy attack"
override def asTics(): Long = 10l
}
case object Crisis extends Unit {
override def name(): String = "crisis"
override def asTics(): Long = 100l
}
implicit def intToCount(count: Int): Count = new Count(count)
def main(args: Array[String]): scala.Unit = {
assert(
(5.of(CockroachSighting) + 9.of(AllergyAttack)) == 1.of(Crisis)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.