Skip to content

Instantly share code, notes, and snippets.

@Jazzatola
Created March 2, 2018 12:57
Show Gist options
  • Save Jazzatola/d2569dcc4a7be065e28c989c0df040f3 to your computer and use it in GitHub Desktop.
Save Jazzatola/d2569dcc4a7be065e28c989c0df040f3 to your computer and use it in GitHub Desktop.
Identity Monad
package com.jamesmaggs.monads
trait Identity[A] { self =>
def run: A
def map[B](f: A => B): Identity[B] =
new Identity[B] { def run = f(self.run) }
def flatMap[B](f: A => Identity[B]): Identity[B] =
new Identity[B] { def run = f(self.run).run }
}
object Identity {
def apply[A](a: A): Identity[A] = new Identity[A] { def run = a }
}
package com.jamesmaggs.monads
import org.scalatest.FunSuite
class IdentityTest extends FunSuite {
val f: Int => Identity[Int] = x => Identity(x + x)
val g: Int => Identity[Int] = x => Identity(x * 2)
val a = 7
test("Left Identity") {
assert(Identity(a).flatMap(f).run == f(a).run)
}
test("Right Identity") {
assert(Identity(a).flatMap(Identity(_)).run == Identity(a).run)
}
test("Associativity") {
assert(Identity(a).flatMap(f).flatMap(g).run == Identity(a).flatMap(i => f(i).flatMap(g)).run)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment