Skip to content

Instantly share code, notes, and snippets.

@j-thepac
Created December 18, 2021 15:16
Show Gist options
  • Save j-thepac/59af3b7d86cb0ca8f55a30d3086b9e7c to your computer and use it in GitHub Desktop.
Save j-thepac/59af3b7d86cb0ca8f55a30d3086b9e7c to your computer and use it in GitHub Desktop.
Monad and Functor
//https://medium.com/beingprofessional/understanding-functor-and-monad-with-a-bag-of-peanuts-8fa702b3f69e
object Monad extends App {
// Functor + unit+ Flatmap = Monad
case class Sugar(weight: Int)
case class Bag[A](content: A) {
def map[B](f: A => B): Bag[B] = Bag(f(content))
def flatMap[B](f: A => Bag[B]): Bag[B] = f(content)
}
def double(sugar: Sugar): Bag[Sugar] = Bag(Sugar(sugar.weight * 2))
def half(sugar: Sugar): Sugar = Sugar(sugar.weight / 2)
val halfSugarBag: Bag[Sugar] = Bag(Sugar(1)).map(sugar => half(sugar))
val doubleSugarBag = Bag(Sugar(1)).flatMap(sugar => double(sugar))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment