Kotlin专题禅与计算机程序设计艺术我的Kotlin之旅

Kotlin(十七)函数式编程<4>

2021-02-28  本文已影响0人  zcwfeng

类型代替异常处理

Kotlin里面摒弃强制异常捕获检查机制,再编译时期尽量发现错误

抛出异常做法本身是一种副作用,破坏了“引用透明性”。但是任何程序要对具体错误捕捉并且给出正确反馈,可以利用Monad这种更抽象的数据结构,代替异常处理错误。用类型处理错误,这种方式有一个优点,类型安全。

1. Option 与 OptionT

Kotlin可空类型,某种程度就是利用类型代替Checked Exception来防止NPE(NullPointerException缩写)问题。

@Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE")
inline fun <A> Kind<Option.K, A>.unwrap(): Option<A> =
    this as Option<A>


sealed class Option<out A> : Kind<Option.K, A> {
  object K
}

data class Some<V>(val value: V) : Option<V>()
object None : Option<Nothing>()

Kind<Option.K,A> 和 Kind<List.K,A> 模拟一种高阶类型,用它们可以表示存在值或者空值两种状态。分别对应数据类Some和单利对象None实现Option<Nothing>()

根据前面的知识,我们可给Option类型扩展flatMap,pure和map方法,从而让它具有组合能力

object OptionMonad : Monad<Option.K> {
  override fun <A, B> Kind<Option.K, A>.flatMap(f: (A) -> Kind<Option.K, B>): Kind<Option.K, B> {
    val oa = this
    return when (oa) {
      is Some -> f(oa.value)
      else -> None
    }
  }

  override fun <A> pure(a: A): Kind<Option.K, A> {
    return Some(a)
  }
}

结合前面的StdIO,实现一个readInt 方法,对Option<Int> 变量进行求和操作,通过errorHandleWithOption 处理这些错误

fun readInt():StdIO<Option<Int>>{
    return StdIOMonad.run {
        val r = StdIO.read().map {
            when{
                it.matches(Regex("[0-9]+")) -> Some(it.toInt())
                else -> None
            }
        }
        r.unwrap()
    }
}

fun addOption(oa:Option<Int>,ob:Option<Int>) = {
    OptionMonad.run {
        oa.flatMap {a->
            ob.map { b -> a + b }
        }
    }
}

fun errorHandleWithOption(){
    StdIOMonad.run {
        readInt().flatMap { oi ->
            readInt().flatMap { oj ->
                val r = addOption(oi,oj)
                var display = when(r){
                    is Some<*> -> r.value.toString()
                    else -> ""
                }
                StdIO.write(display)
            }

        }
    }
}

测试

println(addOption(Some<Int>(11), Some<Int>(22)).invoke())

当前的方法来说,当第一次读值出现错误,理想状态是马上返回非正常的结果,当前依旧会进行第二次读值。
对StdIO进行组合,内部是Option类型,每次必须对Option类型的值进行模式匹配,然后处理。如果把StdIO<Option<T>>的StdIO<Option<*>>看成一个整体,可以直接对T进行组合操作。

回顾下前面Applicative,Functor


interface Functor<F> {
  abstract fun <A, B> Kind<F, A>.map(f: (A) -> B): Kind<F, B>
}

interface Applicative<F> : Functor<F> {
  fun <A> pure(a: A): Kind<F, A>
  fun <A, B> Kind<F, A>.ap(f: Kind<F, (A) -> B>): Kind<F, B>
  override fun <A, B> Kind<F, A>.map(f: (A) -> B): Kind<F, B> {
    return ap(pure(f))
  }
}

OptionT的数据类型

package top.zcwfeng.kt.functional

import top.zcwfeng.kt.functional.typeclass.*

data class OptionT<F, A>(val value: Kind<F, Option<A>>) {
  object K

  companion object {
    fun <F, A> pure(AP: Applicative<F>, v: A): OptionT<F, A> {
      return OptionT(AP.pure(Some(v)))
    }

    fun <F, A> none(AP: Applicative<F>): OptionT<F, A> {
      return OptionT(AP.pure(None))
    }

    fun <F, A> liftF(M: Functor<F>, fa: Kind<F, A>): OptionT<F, A> {
      val v = M.run {
        fa.map {
            Some(it)
        }
      }
      return OptionT(v)
    }
  }

  fun <B> flatMap(M: Monad<F>, f: (A) -> OptionT<F, B>): OptionT<F, B> {
    val r = M.run {
      value.flatMap { oa ->
        when (oa) {
          is Some -> f(oa.value).value
          else -> M.pure(None)
        }
      }
    }
    return OptionT(r)
  }

  fun <B> map(F: Functor<F>, f: (A) -> B): OptionT<F, B> {
    val r: Kind<F, Option<B>> = F.run {
      value.map { ov ->
        OptionMonad.run {
          ov.map(f).unwrap()
        }
      }
    }
    return OptionT(r)
  }

}


fun main(args: Array<String>) {
  val fa1 = OptionT.pure(ListMonad, 1)
  val fa2 = OptionT.pure(ListMonad, 2)
  val fa3 = fa1.flatMap(ListMonad) { a1: Int ->
    fa2.map(ListMonad) { a2: Int ->
      a1 + a2
    }
  }
  println(fa3.value)
}

和Option不一样,OptionT的参数Kind<F, Option<A>>,如果存在Option类型值,我们可以给他套上类型构造器F然后在包裹OptionT类型

OptionT的pure方法和none方法和之前的一样,接受参数只需要一个pure方法,所以参数是Applicative<F> 就行,没必要Monad<F>

核心方法flatMap定义一个表达式函数体,flatMap返回一个lambda,类型((A)-> OptionT<F,B>)-> Option<F,B>

fun errorHandleWithOptionT(){
    fun readInt(): OptionT<StdIO.K, Int> {
        val r =  StdIOMonad.run {
            val r = StdIO.read().map {
                when {
                    it.matches(Regex("[0-9]+")) -> Some(it.toInt())
                    else -> None
                }
            }
            r.unwrap()
        }
        return OptionT(r)
    }
    val add = readInt().flatMap(StdIOMonad){i ->
        readInt().flatMapF(StdIOMonad){j->
            StdIO.write((i+j).toString())
        }
    }
    add.getOrElseF(StdIOMonad,StdIO.write("input error"))
}

OptionT增加两个方法

fun <B> flatMapF(M: Monad<F>, f: (A) -> Kind<F, B>): OptionT<F, B> {
    val ob = M.run {
      value.flatMap {
        when (it) {
          is Some -> f(it.value).map {
            Some(it)
          }
          else -> pure(None)
        }
      }
    }
    return OptionT(ob)
  }

  fun getOrElseF(M:Monad<F>,fa:Kind<F,A>):Kind<F,A>{
    return M.run {
      value.flatMap {
        when(it){
          is Some -> M.pure(it.value)
          else -> fa
        }
      }
    }
  }

2. Either 与 EitherT

显示业务错误的种类多样化,不仅仅一种。针对不同种类,最好能提供不同的处理方式。

思考一个简化版本

sealed class Either<A, B>(){
  class Right<B>(val value: B) : Either<A, B>()
  class Left<A>(val value: A) : Either<A, B>()
}

实现非A即B,Option也可以认为是特殊的Either,知识代表是否存在。Either更加通用,但是没有支持高阶类型。定义一个新的Either,那么需要定义一个Kind2<F,A,B>

typealias Kind2<F, A, B> = Kind<Kind<F, A>, B>

Either 的实现

@Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE")
inline fun <A, B> Kind2<Either.K, A, B>.unwrap(): Either<A, B> =
  this as Either<A, B>


sealed class Either<out A, out B> : Kind2<Either.K, A, B> {
  object K
}

data class Right<B>(val value: B) : Either<Nothing, B>()
data class Left<A>(val value: A) : Either<A, Nothing>()

根据前面构建的套路,需要给Either增加一个EitherMonad

class EitherMonad<C> : Monad<Kind<Either.K, C>> {
  override fun <A, B> Kind<Kind<Either.K, C>, A>.flatMap(f: (A) -> Kind<Kind<Either.K, C>, B>): Kind<Kind<Either.K, C>, B> {
    val eab = this
    return when (eab) {
      is Right -> f(eab.value)
      is Left -> eab
      else -> TODO()
    }
  }

  override fun <A> pure(a: A): Kind<Kind<Either.K, C>, A> {
    return Right(a)
  }
}

Either 也存在同样问题,在面临多种组合场景的情况,还是需要类似OptionT的Either版本解决问题,同样的命令方式,他是EitherT
类似OptionT改进思路,定义EitherT


data class EitherT<F, L, A>(val value: Kind<F, Either<L, A>>) {
  companion object {
    fun <F, A, B> pure(AP: Applicative<F>, b: B): EitherT<F, A, B> {
      return EitherT(AP.pure(Right(b)))
    }
  }

  fun <B> flatMap(M: Monad<F>, f: (A) -> EitherT<F, L, B>): EitherT<F, L, B> {
    val v = M.run {
      value.flatMap { ela ->
        when (ela) {
          is Left -> M.pure(Left(ela.value))
          is Right -> f(ela.value).value

        }
      }
    }
    return EitherT(v)
  }

  fun <B> map(F: Functor<F>, f: ((A) -> B)): EitherT<F, L, B> {
    val felb = F.run {
      value.map { ela ->
        EitherMonad<L>().run {
          ela.map(f).unwrap()
        }
      }
    }
    return EitherT(felb)
  }
}

fun main(args: Array<String>) {
  val e1 = EitherT.pure<List.K, String, Int>(ListMonad, 1)
  val e2 = EitherT.pure<List.K, String, Int>(ListMonad, 2)
  val e3 = e1.flatMap(ListMonad) { v1 ->
    e2.map(ListMonad) { v2 ->
      v1 + v2
    }
  }
  println(e3.value)
}

结合之前读值求和例子,将基于Either例子改写

fun errorHandlerWithEitherT() {
    fun readInt(): EitherT<StdIO.K, String, Int> {
        val r = StdIOMonad.run {
            StdIO.read().map {
                when {
                    it.matches(Regex("[0-9]+")) -> Right(it.toInt())
                    else -> Left("$(it) is not a number ")
                }
            }
        }
        return EitherT(r)
    }

    val add = readInt().flatMap(StdIOMonad) { i ->
        readInt().flatMapF(StdIOMonad) { j ->
            StdIO.write((i + j).toString())
        }
    }
    
    add.valueOrF(StdIOMonad) { err ->
        StdIO.write(err)
    }
}
上一篇下一篇

猜你喜欢

热点阅读