如果A和B是单子,如何将A [B [C]]转换为B [A [C]]?

编程入门 行业动态 更新时间:2024-10-28 02:30:37
本文介绍了如果A和B是单子,如何将A [B [C]]转换为B [A [C]]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找一种更通用的解决方案,该方案利用monad(可能还有monoid)来实现与 if( xs.contains(None) ) None else Some(xs.flatten)用于类型Seq[Option[A]]的xs.

I'm looking for a more general solution which exploits monads (and monoids possibly) to achieve the same as if( xs.contains(None) ) None else Some(xs.flatten) does for xs of type Seq[Option[A]].

如何使用Scalaz做到这一点?我觉得我缺少明显的东西.

How can I do that with Scalaz? I feel like I'm missing something evident.

推荐答案

拥有两个单子既不足够(对于M)又绰绰有余(对于N)—当然,这加起来还不够—但是,如果M具有Traverse实例,而N具有Applicative实例,则可以使用sequence.例如:

Having two monads is both not enough (for M) and more than enough (for N)—which adds up to not enough, of course—but if M has a Traverse instance and N has an Applicative instance, you can use sequence. For example:

import scalaz._, Scalaz._ def foo[A](xs: List[Option[A]]): Option[List[A]] = xs.sequence

这具有您想要的语义.请注意,我使用的是List而不是Seq,因为Scalaz 7不再为Seq提供必要的Traverse实例(尽管您可以轻松编写自己的实例).

This has the semantics you want. Note that I'm using List instead of Seq, since Scalaz 7 no longer provides the necessary Traverse instance for Seq (although you could easily write your own).

您已经注意到,以下内容不会编译:

As you've noticed, the following won't compile:

List(Some(1), Some(45)).sequence

如果在其中扔None也可以:

scala> List(Some(1), None, Some(45)).sequence res0: Option[List[Int]] = None

这是因为推断出的List(Some(1), Some(45))类型将是List[Some[Int]],而我们没有Applicative实例用于Some.

This is because the inferred type of List(Some(1), Some(45)) will be List[Some[Int]], and we don't have an Applicative instance for Some.

Scalaz提供了一个方便的some方法,该方法的工作方式与Some.apply相似,但是为您提供了已经键入为Option的内容,因此您可以编写以下内容:

Scalaz provides a handy some method that works like Some.apply but gives you something that's already typed as an Option, so you can write the following:

scala> List(some(1), some(45)).sequence res1: Option[List[Int]] = Some(List(1, 45))

无需额外输入.

更多推荐

如果A和B是单子,如何将A [B [C]]转换为B [A [C]]?

本文发布于:2023-11-25 05:03:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628441.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单子   转换为   如何将

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!