简体   繁体   English

Scalaz Kleisli的使用益处

[英]Scalaz Kleisli usage benefits

In scalaz Kleisli[M[_], A, B] is a wrapper of A => M[B] , which allows composition of such functions. scalaz Kleisli[M[_], A, B]A => M[B]的包装,它允许组合这些函数。 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] . 例如,如果M[_]是monad,我可以用>=>组成Kleisli[M, A, B]Kleisli[M, B, C]以得到Kleisli[M, A, C]

In a nutshell, Kleisli provides fancy andThens depending on M . 简而言之, Kleisli提供看中andThens根据M Is it correct ? 这是正确的吗 ? Are there other benefits of using Kleisli ? 使用Kleisli还有其他好处吗?

Here are two benefits as examples—I'm sure you could come up with others. 这有两个好处作为例子 - 我相信你可以拿出其他人。

First, it can be useful to abstract over different arrows, such as Kleisli[M, ?, ?] and ? => ? 首先,抽象不同的箭头是有用的,例如Kleisli[M, ?, ?]? => ? ? => ? . 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

Now I can use this on eg Int => Int or Kleisli[Option, Int, Int] : 现在我可以在例如Int => IntKleisli[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
}

And then: 然后:

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

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

(Note that A =?> B is just an alias for Kleisli[Option, A, B] .) (注意A =?> B只是Kleisli[Option, A, B]的别名。)

Second, the fact that Kleisli[F, ?, ?] has a monad instance if F does can also be useful. 其次,如果F确实如此, Kleisli[F, ?, ?]具有monad实例的事实也是有用的。 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 . 例如,请参阅我的答案 ,以演示如何使用ReaderT组合,这只是Kleisli的别名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM