Skip to content

Instantly share code, notes, and snippets.

@bhoggard
Created May 24, 2019 19:28
Show Gist options
  • Save bhoggard/60f09c06c8f2594e5c386c48a1c1d3df to your computer and use it in GitHub Desktop.
Save bhoggard/60f09c06c8f2594e5c386c48a1c1d3df to your computer and use it in GitHub Desktop.
// 4.5.6.1
sealed trait TrafficLight {
def next = this match {
case Red => Green
case Green => Yellow
case Yellow => Red
}
}
case object Red extends TrafficLight
case object Green extends TrafficLight
case object Yellow extends TrafficLight
assert(Red.next == Green)
assert(Green.next == Yellow)
assert(Yellow.next == Red)
// 4.5.6.2
sealed trait Calculation
final case class Success(result: Int) extends Calculation
final case class Failure(message: String) extends Calculation
object Calculator {
def +(c: Calculation, b: Int) = c match {
case Success(n) => Success(n + b)
case f @ Failure(_) => f
}
def -(c: Calculation, b: Int) = c match {
case Success(n) => Success(n - b)
case f: Failure => f
}
def /(c: Calculation, b: Int) = c match {
case Success(n) => b match {
case 0 => Failure("Division by zero")
case _ => Success(n / b)
}
case f: Failure => f
}
}
assert(Calculator.+(Success(1), 1) == Success(2))
assert(Calculator.-(Success(1), 1) == Success(0))
assert(Calculator.+(Failure("Badness"), 1) == Failure("Badness"))
assert(Calculator./(Success(4), 2) == Success(2))
assert(Calculator./(Success(4), 0) == Failure("Division by zero"))
assert(Calculator./(Failure("Badness"), 0) == Failure("Badness"))
// 4.6.3.1
sealed trait IntList {
def length: Int = this match {
case End => 0
case Pair(h, t) => 1 + t.length
}
def product: Int = this match {
case End => 1
case Pair(h, t) => h * t.product
}
def double: IntList = this match {
case End => End
case Pair(h, t) => Pair(2 * h, t.double)
}
}
case object End extends IntList
final case class Pair(head: Int, tail: IntList) extends IntList
val example: Pair = Pair(1, Pair(2, Pair(3, End)))
assert(example.length == 3)
assert(example.tail.length == 2)
assert(End.length == 0)
assert(example.product == 6)
assert(example.tail.product == 6)
assert(End.product == 1)
assert(example.double == Pair(2, Pair(4, Pair(6, End))))
assert(example.tail.double == Pair(4, Pair(6, End)))
assert(End.double == End)
// 4.6.3.2
sealed trait Tree {
def sum: Int = this match {
case Leaf(v) => v
case Node(l, r) => l.sum + r.sum
}
def double: Tree = this match {
case Leaf(v) => Leaf(v * 2)
case Node(l, r) => Node(l.double, r.double)
}
}
final case class Leaf(value: Int) extends Tree
final case class Node(left: Tree, right: Tree) extends Tree
val left = Node(Leaf(1), Leaf(2))
val right = Node(Leaf(3), Leaf(4))
val treeExample = Node(left, right)
assert(treeExample.sum == 10)
assert(treeExample.double == Node(Node(Leaf(2), Leaf(4)), Node(Leaf(6), Leaf(8))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment