Created
December 18, 2021 15:16
-
-
Save j-thepac/59af3b7d86cb0ca8f55a30d3086b9e7c to your computer and use it in GitHub Desktop.
Monad and Functor
This file contains hidden or 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
//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