Skip to content

Instantly share code, notes, and snippets.

@anupkalburgi
Last active March 24, 2019 23:30
Show Gist options
  • Save anupkalburgi/70d6f0625c25bbfd34f1cc0a575a2023 to your computer and use it in GitHub Desktop.
Save anupkalburgi/70d6f0625c25bbfd34f1cc0a575a2023 to your computer and use it in GitHub Desktop.
learning monads
object Test {
trait Monad[T] {
def flatMap[U](f: T => Monad[U]): Monad[U]
}
def unit[T](x: T): Monad[T] = ???
// Associative => m.flatMap(f).flatMap(g) == m.flatMap(x => f(x).flatMap(g))
//
// left Identity => unit(x).flatMap(f) == f(x)
// right identity => m.flatMap(unit) == m
// Monads are very useful to write complex flow controls or pattern matching and for more complex use for or do
// Strategy for combining computations into a complex computations
//What are the consequnces of breaking the associative law
}
object tmp1 {
def readInt: Option[Int] = ???
def readAndAddOne: Option[Int] = readInt match {
case Some(x) => Some(x + 1)
case None => None
}
def readPositiveInt: Option[Int] = readInt match {
case Some(x) if x > 0 => Some(x)
case _ => None
}
def readAndSum: Option[Int] = readInt match {
case Some(x) => readInt match {
case Some(y) => Some(x + y)
case _ => None
}
case _ => None
}
}
object tmp2 {
def readInt: Option[Int] = ???
def readAndAddOne: Option[Int] = readInt.map(_+ 1)
def readPositiveInt: Option[Int] = readInt.filter(x => x > 0)
def readAndSum: Option[Int] = for {
x <- readInt
y <- readInt
} yield x + y
def readAndSum2: Option[Int] = readInt.flatMap(x => readInt.map(y => x + y))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment