总结两个选择 [英] Summing up two options

查看:74
本文介绍了总结两个选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个可选的Ints(都可以是Some或None):

Let's say I have two optional Ints (both can be Some or None):

val one : Option[Int] = Some(1)
val two : Option[Int] = Some(2)

我的问题如下:使用Scalas出色的收集方法,有没有什么聪明的方法可以对它们进行求和?我意识到我可以将它们合并到一个集合中,然后flatten并像这样使用reduceLeftOption:

My question is the following: Are there any intelligent way to sum them op using Scalas brilliant collection-methods? I realize that I could merge them into a collection, flatten it and use reduceLeftOption like so:

(one :: two :: Nil).flatten.reduceLeftOption(_ + _)     // Some(3)

但是,上述解决方案意味着创建一个新系列,并生活在一个发达而发达的世界中,而这可能需要我投入自己的所有其他第一世界活动中所花费的时间.在一个像我们这样的程序员变得越来越奢侈的世界中,必须对此有一个或多个豪华的第一世界答案,对吧?

But, the solution above means creating a new collection, and living in a rich and developed world that takes time from all the other first world activities I might immerse myself into. And in a world where programming gets more and more luxurious for programmers like us, there must be one or more luxurious first world answer(s) to this, right?

因此,为了说明问题,下面是一些示例:

So to spell things out, here are some examples:

如果one = Some(1)two = Some(2),我们应该有Some(3)

If one = Some(1) and two = Some(2) we should have Some(3)

如果one = Some(1)two = None,我们应该有Some(1)

If one = Some(1) and two = None we should have Some(1)

如果one = Nonetwo = Some(2),我们应该有Some(2)

If one = None and two = Some(2) we should have Some(2)

如果onetwo均为None,则我们应设置为None,因为onetwo都不能正确求和.

If both one and two are None we should have None, since neither one or two can be summed correctly.

希望能澄清一些事情:-)

Hope that clarified things :-)

推荐答案

强制性scalaz答案是使用scalaz Option monoid:

obligatory scalaz answer is to use the scalaz Option monoid:

scala> one |+| two
res0: Option[Int] = Some(3)

关于无,它将做您想要的事情:

It will do what you want with respect to None:

scala> two |+| None
res1: Option[Int] = Some(2)

scala> none[Int] |+| none[Int]
res2: Option[Int] = None

none方法不是scalaz的方法,它有助于类型推断,因为它代替返回None <: Option[Nothing]而不是返回Option[Int],而Some的方法类似,它为给定的A返回Option [A]而不是一些[A]:

That none method is a method from scalaz which helps with type inference because instead of returning None <: Option[Nothing] it returns a Option[Int], there is a similar method from Some which returns an Option[A] for any given A instead of a Some[A]:

scala> 1.some |+| 2.some
res3: Option[Int] = Some(3)

这篇关于总结两个选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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