Skip to content

Instantly share code, notes, and snippets.

@lispyclouds
Last active May 21, 2020 05:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lispyclouds/44106d5e5bf4fe70f16619aa002c90db to your computer and use it in GitHub Desktop.
Save lispyclouds/44106d5e5bf4fe70f16619aa002c90db to your computer and use it in GitHub Desktop.
Dotty ADTs
import scala.io.StdIn
// Result[+T] is a Monoid with flatMap as the join fn
enum Result[+T] {
case Success(value: T)
case Failure(exception: Throwable)
// bind hence a Monad
def flatMap[U](f: T => Result[U]) =
this match {
case Success(value) => f(value)
case _ => this
}
// makes this a Functor
def map[U](f: T => U) =
this match {
// f(v) can safely blow up due to the construction of the unit
case Success(value) => flatMap(v => unit(f(v)))
case _ => this
}
}
// The `=> T` is SUPER IMPORTANT here!!
def unit[T](f: => T) =
try Result.Success(f) catch {
case e: Throwable => Result.Failure(e)
}
def readInt = {
print("Enter a number: ")
StdIn.readInt()
}
def safeReadAndAdd(prev: Int) =
try Result.Success(prev + readInt) catch {
case e: Throwable => Result.Failure(e)
}
object M {
def main(args: Array[String]) = {
val r1 = safeReadAndAdd(0).flatMap(safeReadAndAdd)
.flatMap(safeReadAndAdd)
.map(_ / readInt)
val r2 = for {
n1 <- safeReadAndAdd(0)
n2 <- safeReadAndAdd(n1)
n3 <- safeReadAndAdd(n2)
} yield n3 / readInt
println(r1)
println(r2)
}
}
@lispyclouds
Copy link
Author

To compile and run:

  • Install Dotty
  • dotc M.scala
  • dotr M

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment