DiveIntoKotlin/DiveIntoKotlinSamples

10.4 函数式编程,书中代码错误

qbosen opened this issue · 0 comments

书里面有多处高阶函数返回值不明确。
贴一下10.4 Option中的坑

  • stdIOrunFlatMap需要返回值
fun <A> perform(stdIO: StdIO<A>): A {
    fun <C, D> runFlatMap(fm: FlatMap<C, D>): D {
        return perform(fm.f(perform(fm.fa)))
    }
    return when (stdIO) {
        is ReadLine -> readLine() as A
        is Pure<A> -> stdIO.a
        is WriteLine -> println(stdIO.line) as A
        is FlatMap<*, A> -> runFlatMap(stdIO)
    }
}
  • Option的返回值
fun addOption(oa: Option<Int>, ob: Option<Int>): Option<Int> {
    return OptionMonad.run {
        oa.flatMap { a -> ob.map { b -> a + b } }
    }.unwrap()
}