Skip to content

Instantly share code, notes, and snippets.

@monkey-codes
Last active June 9, 2023 23:20
Show Gist options
  • Select an option

  • Save monkey-codes/79c9a7d1ecdeee798199ab0eb6d286ca to your computer and use it in GitHub Desktop.

Select an option

Save monkey-codes/79c9a7d1ecdeee798199ab0eb6d286ca to your computer and use it in GitHub Desktop.
Id Monad
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
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