组成返回选项的函数 [英] Composing functions that return an option

查看:82
本文介绍了组成返回选项的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些类型为Int => Option[Int]的函数:

Suppose I have a few functions of type Int => Option[Int]:

def foo(n: Int): Int => Option[Int] = {x => if (x == n) none else x.some}

val f0 = foo(0)
val f1 = foo(1)

我可以用>=>编写它们,如下所示:

I can compose them with >=> as follows:

val composed: Int => Option[Int] = Kleisli(f0) >=> Kleisli(f1)

假设现在我需要从列表中组合所有功能:

Suppose now I need to compose all functions from a list:

val fs: List[Int => Option[Int]] = List(0, 1, 2).map(n => foo(n))

我可以用mapreduce做到这一点:

I can do it with map and reduce:

val composed: Int => Option[Int] = fs.map(f => Kleisli(f)).reduce(_ >=> _)

(上面的composed)可以简化吗?

Can it (the composed above) be simplified ?

推荐答案

如果要使用合成Monoid(而不是运行每个结果并求和结果" monoid),则必须使用Endomorphic包装器:

If you want the composition monoid (as opposed to the "run each and sum the results" monoid), you'll have to use the Endomorphic wrapper:

import scalaz._, Scalaz._

val composed = fs.foldMap(Endomorphic.endoKleisli[Option, Int])

然后:

scala> composed.run(10)
res11: Option[Int] = Some(10)

kleisli箭头的monoid仅需要一个输出类型的monoid实例,而composite monoid则需要输入和输出类型相同,因此有意义的是后者只能通过包装器使用.

The monoid for kleisli arrows only requires a monoid instance for the output type, while the composition monoid requires the input and output types to be the same, so it makes sense that the latter is only available via a wrapper.

这篇关于组成返回选项的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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