Further demistifying the Monad in Scala: a Category Theory approach

Photo by Lucien Kolly on Unsplash

Algebraic structures

Category

Monoid

Instead of giving you the traditional rules of addition, I could as well give you the rules of composing adders, without any loss of information.

(I took the photo from here)

Functor

List(1, 2, 3).map((x: Int) => x.toString)

Monad

Three monad definitions and monad laws

def compose: (A => F[B]) => (B => F[C]) => A => F[C]
def unit: A => F[A]
(A => F[B]) => (B => F[B]) => A => F[B]
(A => F[Whatever]) => (Whatever => F[Whatever]) => A => F[Whatever]
trait Monad[F[_]] {  def flatMap[A, B](fa: F[A], f: A => F[B]): F[B] = ???  def compose[A, B, C](f1: A => F[B], f2: B => F[C]): A => F[C] = {
    a => flatMap[B, C](f1(a), f2)
  }
}
trait Monad[F[_]] {

  def compose[A, B, C](f1: A => F[B], f2: B => F[C]): A => F[C] = ???

  def flatMap[A, B](fa: F[A], f: A => F[B]): F[B] = {
    compose[Unit, A, B]((u: Unit) => fa, f)()
  }
}

Summary

Final word

freeCodeCamp.org

This is no longer updated. Go to https://freecodecamp.org/news instead

Sinisa Louc

Written by

Backend Engineer at Spotcap (https://www.spotcap.com), Berlin. I blog about Scala and functional programming in general. Find me on Twitter (link below).

freeCodeCamp.org

This is no longer updated. Go to https://freecodecamp.org/news instead