-
-
Save monkey-codes/79c9a7d1ecdeee798199ab0eb6d286ca to your computer and use it in GitHub Desktop.
Id Monad
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
| data class IdMonad<out A>(val a: A) { | |
| companion object { | |
| fun <A> unit(a: A): Id<A> = Id(a) | |
| } | |
| fun <B> flatMap(f: (A) -> Id<B>): Id<B> = f(this.a) | |
| fun <B> map(f: (A) -> B): Id<B> = unit(f(this.a)) | |
| } | |
| ... | |
| val x = IdMonad | |
| .unit("hello") | |
| .flatMap { Id.unit("$it world") } | |
| println(x.a) // hello world |
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
| sealed class OptionMonad<out A> { | |
| object None : OptionMonad<Nothing>() | |
| data class Some<out A>(val value: A) : OptionMonad<A>() | |
| companion object { | |
| fun <T> unit(value: A): OptionMonad<A> { | |
| return Some(value) | |
| } | |
| } | |
| fun <B> flatMap(f: (A) -> OptionMonad<B>): OptionMonad<B> { | |
| return when (this) { | |
| is Some -> f(value) | |
| is None -> None | |
| } | |
| } | |
| } | |
| fun findSquareRoot(n: Double): OptionMonad<Double> { | |
| return if (n >= 0) { | |
| OptionMonad.unit(Math.sqrt(n)) | |
| } else { | |
| OptionMonad.None | |
| } | |
| } | |
| val result = OptionMonad.unit(25.0) | |
| .flatMap(::findSquareRoot) | |
| .flatMap(::findSquareRoot) | |
| when (result) { | |
| is OptionMonad.Some -> println("Result: ${result.value}") | |
| is OptionMonad.None -> println("Error: Value is absent") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment