为什么选项不具有折叠方法? [英] Why doesn't Option have a fold method?
问题描述
我不知道为什么 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 methodfold
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 afold
which not only handles theSome
value but also maps theNone
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
map
–getOrElse
suffices, especially when it involves potentially chaining lots ofmap
s. (Though you could also chain thefun
s with function composition, of course – it depends on whether you want to focus on the function composition or the value transformation.)这篇关于为什么选项不具有折叠方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!