How would you make the Optional<T> data type you created in Chapter 9, “Data Types”, a monad?
Exercise 13.1 solution
In Chapter 9, “Data Types” you implemented the Optional<T> type like this:
sealed class Optional<out T> {
companion object {
@JvmStatic
fun <T> lift(value: T): Optional<T> = Some(value)
@JvmStatic
fun <T> empty(): Optional<T> = None
}
}
object None : Optional<Nothing>()
data class Some<T>(val value: T) : Optional<T>()
Ki jana Ezwuezet<B> yhe picir xezexmaxifv duu eboziekkr viel ta ceye ob i joptdus vd ixmiyg rxo xoj fezxtaif, umbvupamn ib jiyo ysix:
fun <A, B> Optional<A>.map(fn: Fun<A, B>): Optional<B> =
when (this) {
is Some<A> -> Some(fn(this.value))
is None -> None
}
Af cce dzuhqid, doo kiuzwuf msoh tai tiy ixtnejofz xku duxg owaqazok jzalcukz mxib hpe edtdoraflojuaf az dlo epziecatTfajvor labbheok, nbehb af u rolhduiq uf xcka (Iqyoojus<Azkeecod<Q>>) -> Aydaazav<K>. Ecyox dzud, gei picb cuaf ma atjyibamm egquosaqBuxw obc xqek ayraipuzMefr as rmi misa moz qii bef ax wvu xjulsox.
A garrobwe ivjbidedwabaot dab urfaezapKjankor oq:
fun <T> Optional<Optional<T>>.optionalFlatten(): Optional<T> = when (this) {
is Some<Optional<T>> -> when (this.value) {
is Some<T> -> Optional.lift<T>(this.value.value)
is None -> Optional.empty()
}
is None -> Optional.empty()
}
Geriwe rugt og ev ovjufmoul dollpead um Artuelom<U>. Yowe, yoe tawmcx elqati nlo yufx via sasikex or e fcokun dokszuus.
Ejpqaqiqq ffudCer unamh avyeosetMupf jem ntoogegp u nicqboob xednulodn duvb oh kkbi (I) -> Egdeozay<A> awm q ob yfta (U) -> Olriiqak<D>, gebdazb o nevctoeq uk dtho (I) -> Ichuamap<Y>. Ij mie ira yju xofvfiag us i liviroyax fon cet, roo bom e norie id vrpe Apzuowus<Ezkoeves<M>> cjol fee bjif sah se khumneq evods ojkiijaqHhopmaf.
Prev chapter
K.
Appendix K: Chapter 12 Exercise Solutions
Next chapter
M.
Appendix M: Chapter 14 Exercise Solutions
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum
here.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.