Created
March 2, 2018 12:57
-
-
Save Jazzatola/d2569dcc4a7be065e28c989c0df040f3 to your computer and use it in GitHub Desktop.
Identity Monad
This file contains 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
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 } | |
} |
This file contains 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
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