Skip to content

Instantly share code, notes, and snippets.

@Adriandmen
Created April 21, 2022 15:36
Show Gist options
  • Save Adriandmen/7f10280ad6586f94fdec1f849e4dc201 to your computer and use it in GitHub Desktop.
Save Adriandmen/7f10280ad6586f94fdec1f849e4dc201 to your computer and use it in GitHub Desktop.
// The main interface of a Monad.
trait Monad[M[_]] {
def unit[A](a: A): M[A]
def flatMap[A, B](fa: M[A])(f: A => M[B]): M[B]
}
// Maybe and its concrete 'implementations'.
sealed trait Maybe[+A]
case class Just[+A](a: A) extends Maybe[A]
case object Nothing extends Maybe[Nothing]
// Companion object, which implements the Monad interface.
object Maybe extends Monad[Maybe] {
def unit[A](a: A): Maybe[A] = Just(a)
def flatMap[A, B](fa: Maybe[A])(f: A => Maybe[B]): Maybe[B] = fa match {
case Just(a) => f(a)
case Nothing => Nothing
}
}
object Monads {
def main(args: Array[String]): Unit = {
val before = List(Just(1), Just(2), Nothing, Just(4), Nothing, Just(6))
val after = before map { m => Maybe.flatMap(m) { x => Maybe.unit(x * 60) } }
println(before) // output: List(Just(1), Just(2), Nothing, Just(4), Nothing, Just(6))
println(after) // output: List(Just(60), Just(120), Nothing, Just(240), Nothing, Just(360))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment