简体   繁体   English

Seq [Option [T]]到Option [Seq [T]]的“自然”功能是否有名称?

[英]Does the “natural” function from Seq[Option[T]] to Option[Seq[T]] have a name?

Does this function (or perhaps some monadic generalisation of it) have an established name? 这个函数(或者它的一些monadic泛化)是否具有已建立的名称?

def foo[T](in: Seq[Option[T]]): Option[Seq[T]] = {
    val res = in.flatten.seq
    if (res.length == in.length) Some(res) else None
}

Is there a more elegant implementation? 是否有更优雅的实施?

As already suggested in the comments, the function from Seq[M[A]] to M[Seq[A]] (where M is a monad) is usually referred to as sequence . 正如在评论中已经提出的,从Seq[M[A]]M[Seq[A]] (其中M是monad)的函数通常被称为sequence

The Haskell definition of it is: Haskell的定义是:

Evaluate each action in the sequence from left to right, and collect the results. 从左到右评估序列中的每个操作,并收集结果。

There's no generic implementation of it in the scala standard library, but you can see an example for the Future type here: https://github.com/scala/scala/blob/v2.10.3/src/library/scala/concurrent/Future.scala#L487-L491 在scala标准库中没有它的通用实现,但你可以在这里看到Future类型的一个例子: https//github.com/scala/scala/blob/v2.10.3/src/library/scala/concurrent/ Future.scala#L487-L491

You can find generic implementations of sequence in libraries such as cats or scalaz . 您可以在诸如catsscalaz等库中找到sequence通用实现。

One thing to notice, is that sequence is a specific case of a more generic operation, usually called traverse . 需要注意的一点是, sequence是更通用操作的特定情况,通常称为traverse

Haskell defines traverse as Haskell将traverse定义为

Map each element of a structure to an action, evaluate these actions from left to right, and ignore the results. 将结构的每个元素映射到一个动作,从左到右评估这些动作,并忽略结果。

Now, given the definition, sequence can be implemented in terms of traverse , simply by using the identity function ( x => x ) as the map operation of traverse . 现在,给定定义, sequence可以用traverse来实现,只需使用标识函数( x => x )作为traverse的映射操作即可。

If you take a look at the implementations mentioned above, you'll find that they all leverage this generalization and they all use traverse to implement sequence . 如果你看一下上面提到的实现,你会发现它们都利用了这种泛化,它们都使用traverse来实现sequence

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

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