为什么选项不具有折叠方法? [英] Why doesn't Option have a fold method?

查看:185
本文介绍了为什么选项不具有折叠方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么 scala.Option 没有一个方法 fold 像这样定义:

  fold(ifSome:A => B,ifNone:=> B)
pre>

相当于

  map(ifSome).getOrElse(ifNone )

有没有比使用 map + getOrElse

解决方案

您可以:

  opt foldLeft(els)((x,y)=> fun(x))
/ pre>

 (els /:opt)(( x,y)=> fun(x))

(两种解决方案都会评估 els 按值,这可能不是你想要的。感谢 Rex Kerr ,指向它。)



编辑:



但是你真正想要的是Scalaz的 fold ,它不仅处理 cata 一些值,但也映射部分,这是您所描述的)

  opt.cata(fun,els)

定义为(where $ 是pimped的选项值)

  def cata [X]一些:A => X,none:=> X):X =值匹配{
case None => none
case一些(a)=>一些(a)
}

相当于 opt。 map(some).getOrElse(none)



虽然我应该说你应该只使用cata,当它是'更自然'表达方式有很多情况下,一个简单的映射 - getOrElse 就足够了,特别是当它涉及到可能链接很多地图秒。 (虽然你也可以使用函数组合链接 fun s,但这取决于你是否要专注于函数组合或值转换。)


I wonder why scala.Option doesn't have a method fold like this defined:

fold(ifSome: A => B , ifNone: => B)

equivalent to

map(ifSome).getOrElse(ifNone)

Is there no better than using map + getOrElse?

解决方案

You can do:

opt foldLeft (els) ((x, y) => fun(x))

or

(els /: opt) ((x,y) => fun(x))

(Both solutions will evaluate els by value, which might not be what you want. Thanks to Rex Kerr for pointing at it.)

Edit:

But what you really want is Scalaz’s catamorphism cata (basically a fold which not only handles the Some value but also maps the None part, which is what you described)

opt.cata(fun, els)

defined as (where value is the pimped option value)

def cata[X](some: A => X, none: => X): X = value match {
  case None => none
  case Some(a) => some(a)
}

which is equivalent to opt.map(some).getOrElse(none).

Although I should remark that you should only use cata when it is the ‘more natural’ way of expressing it. There are many cases where a simple mapgetOrElse suffices, especially when it involves potentially chaining lots of maps. (Though you could also chain the funs with function composition, of course – it depends on whether you want to focus on the function composition or the value transformation.)

这篇关于为什么选项不具有折叠方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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