Scalaz(14)- Monad:函数组合-Kleisli to Reader

简介:

  Monad Reader就是一种函数的组合。在scalaz里函数(function)本身就是Monad,自然也就是Functor和applicative。我们可以用Monadic方法进行函数组合:


import scalaz._
import Scalaz._
object decompose {
//两个测试函数
val f = (_: Int) + 3                              //> f  : Int => Int = <function1>
val g = (_: Int) * 5                              //> g  : Int => Int = <function1>
//functor
val h = f map g  // f andThen g                   //> h  : Int => Int = <function1>
val h1 = g map f  // f compose g                  //> h1  : Int => Int = <function1>
h(2)  //g(f(2))                                   //> res0: Int = 25
h1(2) //f(g(2))                                   //> res1: Int = 13
//applicative
val k = (f |@| g){_ + _}                          //> k  : Int => Int = <function1>
k(10) // f(10)+g(10)                              //> res2: Int = 63
//monad
val m = g.flatMap{a => f.map(b => a+b)}           //> m  : Int => Int = <function1>
val n = for {
  a <- f
  b <- g
} yield a + b                                     //> n  : Int => Int = <function1>
m(10)                                             //> res3: Int = 63
n(10)                                             //> res4: Int = 63
}

 以上的函数f,g必须满足一定的条件才能实现组合。这个从f(g(2))或g(f(2))可以看出:必需固定有一个输入参数及输入参数类型和函数结果类型必需一致,因为一个函数的输出成为另一个函数的输入。在FP里这样的函数组合就是Monadic Reader。 

但是FP里函数运算结果一般都是M[R]这样格式的,所以我们需要对f:A => M[B],g:B => M[C]这样的函数进行组合。这就是scalaz里的Kleisli了。Kleisli就是函数A=>M[B]的类封套,从Kleisli的类定义可以看出:scalaz/Kleisli.scala


1 final case class Kleisli[M[_], A, B](run: A => M[B]) { self =>
2 ...
3 trait KleisliFunctions {
4   /**Construct a Kleisli from a Function1 */
5   def kleisli[M[_], A, B](f: A => M[B]): Kleisli[M, A, B] = Kleisli(f)
6 ...

Kleisli的目的是把Monadic函数组合起来或者更形象说连接起来。Kleisli提供的操作方法如>=>可以这样理解:

(A=>M[B]) >=> (B=>M[C]) >=> (C=>M[D]) 最终运算结果M[D]

可以看出Kleisli函数组合有着固定的模式:

1、函数必需是 A => M[B]这种模式;只有一个输入,结果是一个Monad M[_]

2、上一个函数输出M[B],他的运算值B就是下一个函数的输入。这就要求下一个函数的输入参数类型必需是B

3、M必须是个Monad;这个可以从Kleisli的操作函数实现中看出:scalaz/Kleisli.scala


/** alias for `andThen` */
  def >=>[C](k: Kleisli[M, B, C])(implicit b: Bind[M]): Kleisli[M, A, C] =  kleisli((a: A) => b.bind(this(a))(k.run))

  def andThen[C](k: Kleisli[M, B, C])(implicit b: Bind[M]): Kleisli[M, A, C] = this >=> k

  def >==>[C](k: B => M[C])(implicit b: Bind[M]): Kleisli[M, A, C] = this >=> kleisli(k)

  def andThenK[C](k: B => M[C])(implicit b: Bind[M]): Kleisli[M, A, C] = this >==> k

  /** alias for `compose` */
  def <=<[C](k: Kleisli[M, C, A])(implicit b: Bind[M]): Kleisli[M, C, B] = k >=> this

  def compose[C](k: Kleisli[M, C, A])(implicit b: Bind[M]): Kleisli[M, C, B] = k >=> this

  def <==<[C](k: C => M[A])(implicit b: Bind[M]): Kleisli[M, C, B] = kleisli(k) >=> this

  def composeK[C](k: C => M[A])(implicit b: Bind[M]): Kleisli[M, C, B] = this <==< k

拿操作函数>=>(andThen)举例:implicit b: Bind[M]明确了M必须是个Monad。

kleisli((a: A) => b.bind(this(a))(k.run))的意思是先运算M[A],接着再运算k,以M[A]运算结果值a作为下一个函数k.run的输入参数。整个实现过程并不复杂。

实际上Reader就是Kleisli的一个特殊案例:在这里kleisli的M[]变成了Id[],因为Id[A]=A >>> A=>Id[B] = A=>B,就是我们上面提到的Reader,我们看看Reader在scalaz里是如何定义的:scalar/package.scala


type ReaderT[F[_], E, A] = Kleisli[F, E, A]
  val ReaderT = Kleisli
  type =?>[E, A] = Kleisli[Option, E, A]
  type Reader[E, A] = ReaderT[Id, E, A]

  type Writer[W, A] = WriterT[Id, W, A]
  type Unwriter[W, A] = UnwriterT[Id, W, A]

  object Reader {
    def apply[E, A](f: E => A): Reader[E, A] = Kleisli[Id, E, A](f)
  }

  object Writer {
    def apply[W, A](w: W, a: A): WriterT[Id, W, A] = WriterT[Id, W, A]((w, a))
  }

  object Unwriter {
    def apply[U, A](u: U, a: A): UnwriterT[Id, U, A] = UnwriterT[Id, U, A]((u, a))
  }

type ReaderT[F[_], E, A] = Kleisli[F, E, A] >>> type Reader[E,A] = ReaderT[Id,E,A]

好了,说了半天还是回到如何使用Kleisli进行函数组合的吧:


//Kleisli款式函数kf,kg
val kf: Int => Option[String] = (i: Int) => Some((i + 3).shows)
                                                  //> kf  : Int => Option[String] = <function1>
val kg: String => Option[Boolean] = { case "3" => true.some; case _ => false.some }
                                                  //> kg  : String => Option[Boolean] = <function1>
//Kleisli函数组合操作
import Kleisli._
val kfg = kleisli(kf) >=> kleisli(kg)             //> kfg  : scalaz.Kleisli[Option,Int,Boolean] = Kleisli(<function1>)
kfg(1)                                            //> res5: Option[Boolean] = Some(false)
kfg(0)                                            //> res6: Option[Boolean] = Some(true)

例子虽然很简单,但它说明了很多重点:上一个函数输入的运算值是下一个函数的输入值 Int=>String=>Boolean。输出Monad一致统一,都是Option。

那么,Kleisli到底用来干什么呢?它恰恰显示了FP函数组合的真正意义:把功能尽量细分化,通过各种方式的函数组合实现灵活的函数重复利用。也就是在FP领域里,我们用Kleisli来组合FP函数。

下面我们就用scalaz自带的例子scalaz.example里的KleisliUsage.scala来说明一下Kleisli的具体使用方法吧:

下面是一组地理信息结构:


1   // just some trivial data structure ,
2   // Continents contain countries. Countries contain cities.
3   case class Continent(name: String, countries: List[Country] = List.empty)
4   case class Country(name: String, cities: List[City] = List.empty)
5   case class City(name: String, isCapital: Boolean = false, inhabitants: Int = 20)

分别是:洲(Continent)、国家(Country)、城市(City)。它们之间的关系是层级的:Continent(Country(City))

下面是一组模拟数据:


val data: List[Continent] = List(
    Continent("Europe"),
    Continent("America",
      List(
        Country("USA",
          List(
            City("Washington"), City("New York"))))),
    Continent("Asia",
      List(
        Country("India",
          List(City("New Dehli"), City("Calcutta"))))))

从上面的模拟数据也可以看出Continent,Country,City之间的隶属关系。我们下面设计三个函数分别对Continent,Country,City进行查找:


def continents(name: String): List[Continent] =
    data.filter(k => k.name.contains(name))       //> continents: (name: String)List[Exercises.kli.Continent]
  //查找名字包含A的continent
  continents("A")                                 //> res7: List[Exercises.kli.Continent] = List(Continent(America,List(Country(U
                                                  //| SA,List(City(Washington,false,20), City(New York,false,20))))), Continent(A
                                                  //| sia,List(Country(India,List(City(New Dehli,false,20), City(Calcutta,false,2
                                                  //| 0))))))
  //找到两个:List(America,Asia)
  def countries(continent: Continent): List[Country] = continent.countries
                                                  //> countries: (continent: Exercises.kli.Continent)List[Exercises.kli.Country]
  //查找America下的国家
  val america =
      Continent("America",
      List(
        Country("USA",
          List(
            City("Washington"), City("New York")))))
                                                  //> america  : Exercises.kli.Continent = Continent(America,List(Country(USA,Lis
                                                  //| t(City(Washington,false,20), City(New York,false,20)))))
  countries(america)                              //> res8: List[Exercises.kli.Country] = List(Country(USA,List(City(Washington,f
                                                  //| alse,20), City(New York,false,20))))
  def cities(country: Country): List[City] = country.cities
                                                  //> cities: (country: Exercises.kli.Country)List[Exercises.kli.City]
  val usa = Country("USA",
            List(
              City("Washington"), City("New York")))
                                                  //> usa  : Exercises.kli.Country = Country(USA,List(City(Washington,false,20), 
                                                  //| City(New York,false,20)))
  cities(usa)                                     //> res9: List[Exercises.kli.City] = List(City(Washington,false,20), City(New Y
                                                  //| ork,false,20))

从continents,countries,cities这三个函数运算结果可以看出它们都可以独立运算。这三个函数的款式如下:

String => List[Continent]

Continent => List[Country]

Country => List[City]

无论函数款式或者类封套(List本来就是Monad)都适合Kleisli。我们可以用Kleisli把这三个局部函数用各种方法组合起来实现更广泛功能:


val allCountry = kleisli(continents) >==> countries
                                                  //> allCountry  : scalaz.Kleisli[List,String,Exercises.kli.Country] = Kleisli(<
                                                  //| function1>)
  val allCity = kleisli(continents) >==> countries >==> cities
                                                  //> allCity  : scalaz.Kleisli[List,String,Exercises.kli.City] = Kleisli(<functi
                                                  //| on1>)
  allCountry("Amer")                              //> res10: List[Exercises.kli.Country] = List(Country(USA,List(City(Washington,
                                                  //| false,20), City(New York,false,20))))
  allCity("Amer")                                 //> res11: List[Exercises.kli.City] = List(City(Washington,false,20), City(New 
                                                  //| York,false,20))

还有个=<<符号挺有意思:


1   def =<<(a: M[A])(implicit m: Bind[M]): M[B] = m.bind(a)(run)

意思是用包嵌的函数flatMap一下输入参数M[A]:


1   allCity =<< List("Amer","Asia")                 //> res12: List[Exercises.kli.City] = List(City(Washington,false,20), City(New 
2                                                   //| York,false,20), City(New Dehli,false,20), City(Calcutta,false,20))

那么如果我想避免使用List(),用Option[List]作为函数输出可以吗?Option是个Monad,第一步可以通过。下一步是把函数款式对齐了:

List[String] => Option[List[Continent]]

List[Continent] => Option[List[Country]]

List[Country] => Option[List[City]]

下面是这三个函数的升级版:


//查找Continent List[String] => Option[List[Continent]]
  def maybeContinents(names: List[String]): Option[List[Continent]] =
    names.flatMap(name => data.filter(k => k.name.contains(name))) match {
       case h :: t => (h :: t).some
       case _ => none
    }                                             //> maybeContinents: (names: List[String])Option[List[Exercises.kli.Continent]]
                                                  //| 
  //测试运行
  maybeContinents(List("Amer","Asia"))            //> res13: Option[List[Exercises.kli.Continent]] = Some(List(Continent(America,
                                                  //| List(Country(USA,List(City(Washington,false,20), City(New York,false,20))))
                                                  //| ), Continent(Asia,List(Country(India,List(City(New Dehli,false,20), City(Ca
                                                  //| lcutta,false,20)))))))
  //查找Country  List[Continent] => Option[List[Country]]
  def maybeCountries(continents: List[Continent]): Option[List[Country]] =
    continents.flatMap(continent => continent.countries.map(c => c)) match {
       case h :: t => (h :: t).some
       case _ => none
    }                                             //> maybeCountries: (continents: List[Exercises.kli.Continent])Option[List[Exer
                                                  //| cises.kli.Country]]
   //查找City  List[Country] => Option[List[Country]]
  def maybeCities(countries: List[Country]): Option[List[City]] =
    countries.flatMap(country => country.cities.map(c => c)) match {
       case h :: t => (h :: t).some
       case _ => none
    }                                             //> maybeCities: (countries: List[Exercises.kli.Country])Option[List[Exercises.
                                                  //| kli.City]]
  
  val maybeAllCities = kleisli(maybeContinents) >==> maybeCountries >==> maybeCities
                                                  //> maybeAllCities  : scalaz.Kleisli[Option,List[String],List[Exercises.kli.Cit
                                                  //| y]] = Kleisli(<function1>)
  maybeAllCities(List("Amer","Asia"))             //> res14: Option[List[Exercises.kli.City]] = Some(List(City(Washington,false,2
                                                  //| 0), City(New York,false,20), City(New Dehli,false,20), City(Calcutta,false,
                                                  //| 20)))

我们看到,只要Monad一致,函数输入输出类型匹配,就能用Kleisli来实现函数组合。


相关文章
|
3月前
|
人工智能
阿里云百炼剩余的免费Token在哪查询?Token免费额度用完即停功能如何开启?
阿里云百炼提供超7000万免费Token(每模型100万,有效期90天),开通后自动到账。剩余额度可在百炼控制台「成本与配额」页实时查询;建议开启“免费额度用完即停”功能,避免超额扣费(生产环境慎用)。在阿里云百炼官网:https://t.aliyun.com/U/fPVHqY 免费领取千万Tokens
359 0
|
3月前
|
弹性计算 人工智能 运维
阿里云轻量应用服务器2核2G200M带宽活动价格说明:38元、68元、79元、459元价格原因解析
本文针对阿里云2核2G峰值200M带宽轻量应用服务器的38元、68元、79元、459元四档价格差异做完整拆解,明确不同用户身份对应的购买权益,同步补充99元、199元同价续费ECS等替代高性价比方案,结合全档位性能对比,帮助不同需求用户精准匹配适配的云服务器选型。
|
5月前
|
数据采集 安全 API
🪪《避坑实录:五家开放平台认证门槛对照(个人/企业/服务商/保证金)》(附Python源码)
《避坑实录》详解淘宝、京东、1688、拼多多、抖店五大开放平台认证门槛:个人号仅限基础查询,调订单必须企业主体;自研需预充值或入云塔;ISV普遍冻结保证金(1万–15万元)并抽成。附Python资质自检工具,开发前一键校验主体、权限与合规性,避免中途被卡。(239字)
|
5月前
|
缓存 API Python
百炼 Qwen3.7-Max 详解:百万上下文、工具调用计费、限流参数、Python 流式调用 Demo
Qwen3.7-Max是阿里云Qwen3.7系列最强纯文本大模型,专为智能体时代设计,擅编程、办公与长周期自主任务。支持Function Calling、缓存等能力,输入上限991K tokens,享免费100万tokens额度及限时5折优惠,可在百炼平台调用。在阿里云百炼官网:https://t.aliyun.com/U/fPVHqY 免费领取千万Tokens
|
存储 定位技术 数据库
如何使用Qchan搭建更好保护个人隐私的本地图床并在公网可访问
如何使用Qchan搭建更好保护个人隐私的本地图床并在公网可访问
465 0
|
12月前
libicu-62.1-6.ky10.x86_64.rpm 安装步骤详解(麒麟V10系统)
本文介绍了在麒麟系统上安装libicu库的完整步骤:先通过rpm命令检查是否已安装,若未安装则下载指定版本的rpm包,使用sudo rpm命令进行安装,并通过验证命令确认安装成功。若出现依赖问题,可使用yum自动解决依赖并完成安装。
1177 4
|
运维 监控 数据可视化
别让运维跪着查日志了!给老板看的“业务观测”大盘才是真香
深夜告警、业务暴跌、全员背锅?一次支付故障暴露传统监控盲区。我们通过业务观测,将技术指标转化为老板听得懂的“人话”,实现从被动救火到主动洞察的跨越。让技术团队不再跪着查日志,而是站着驱动业务增长。
别让运维跪着查日志了!给老板看的“业务观测”大盘才是真香
|
机器学习/深度学习 人工智能 算法
深度学习用于求解车间调度问题,性能如何呢?
基于深度学习来求解车间调度问题,不仅求解速度快,求解的质量也越来越好
998 24
|
算法
关于按位运算与逻辑运算
本文介绍了按位运算与逻辑运算的基础知识,并通过一个实际问题展示了按位运算的应用。按位运算直接对二进制位操作,包括按位与(`&`)、或(`|`)、异或(`^`)、取反(`~`)、左移(`&lt;&lt;`)和右移(`&gt;&gt;`)。逻辑运算则针对布尔表达式,包含逻辑与(`&&`)、或(`||`)、非(`!`)。文中通过“寻找独特数字卡片”例题,利用异或运算特性解决数组中唯一单次出现的数字问题,算法时间复杂度为O(n),空间高效。
828 1
|
人工智能 安全 API
什么是阿里云百炼?
什么是阿里云百炼?
5710 0