Scalaz Kleisli 使用优势 [英] Scalaz Kleisli usage benefits

查看:39
本文介绍了Scalaz Kleisli 使用优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scalaz Kleisli[M[_], A, B] 是<代码>A =>M[B],允许组合这些函数.例如,如果 M[_] 是 monad 我可以组合 Kleisli[M, A, B]Kleisli[M, B, C]>=> 得到 Kleisli[M, A, C].

In scalaz Kleisli[M[_], A, B] is a wrapper of A => M[B], which allows composition of such functions. For instance, if M[_] is monad I can compose Kleisli[M, A, B] and Kleisli[M, B, C] with >=> to get Kleisli[M, A, C].

简而言之,Kleisli 根据 M 提供花哨的 andThens.这是正确的吗 ?使用 Kleisli 还有其他好处吗?

In a nutshell, Kleisli provides fancy andThens depending on M. Is it correct ? Are there other benefits of using Kleisli?

推荐答案

这里有两个好处作为例子——我相信你可以想出其他的.

Here are two benefits as examples—I'm sure you could come up with others.

首先,抽象不同的箭头会很有用,例如 Kleisli[M, ?, ?]?=>?.例如,我可以编写一个泛型函数,该函数将应用一定次数的内同态.

First, it can be useful to abstract over different arrows, such as Kleisli[M, ?, ?] and ? => ?. For example, I can write a generic function that will apply an endomorphism a certain number of times.

def applyX10[Arr[_, _]: Category, A](f: Arr[A, A]) =
  List.fill(10)(Endomorphic(f)).suml

现在我可以在例如Int =>IntKleisli[Option, Int, Int]:

Now I can use this on e.g. Int => Int or Kleisli[Option, Int, Int]:

val f = (_: Int) + 1

val k = Kleisli.kleisli[Option, Int, Int] {
  case i if i % 2 == 0 => Some(i * 3)
  case _ => None
}

然后:

scala> applyX10(f).run(1)
res0: Int = 11

scala> applyX10[=?>, Int](k).run(2)
res1: Option[Int] = Some(118098)

(请注意,A =?> B 只是 Kleisli[Option, A, B] 的别名.)

(Note that A =?> B is just an alias for Kleisli[Option, A, B].)

第二,Kleisli[F, ?, ?] 有一个 monad 实例(如果 F 有)的事实也很有用.例如,请参阅我在此处的回答,以演示如何将 monadic 组合与 ReaderT 结合使用,这只是 Kleisli 的别名.

Second, the fact that Kleisli[F, ?, ?] has a monad instance if F does can also be useful. See for example my answer here for a demonstration of how you can use monadic composition with ReaderT, which is just an alias for Kleisli.

这篇关于Scalaz Kleisli 使用优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆