Last active
May 21, 2020 05:13
-
-
Save lispyclouds/44106d5e5bf4fe70f16619aa002c90db to your computer and use it in GitHub Desktop.
Dotty ADTs
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.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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To compile and run:
dotc M.scala
dotr M