折叠选项列表以查找第一个或最后一个 [英] Folding over a list of Options to Find First or Last Some

查看:43
本文介绍了折叠选项列表以查找第一个或最后一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试折叠选项列表,以便返回第一个(或最后一个) Some 值或 None 如果没有任何 Some 值.

I'm trying to fold over a list of Options in order return the first(or last) Some value or None if there aren't any Some values.

scala> val opts = List(None, Some(1), None, Some(2), None)
opts: List[Option[Int]] = List(None, Some(1), None, Some(2), None)

scala> opts foldLeft(None)((a,io) => a match { case None => io; case Some(i) =>
a})
<console>:9: error: object None does not take parameters
              opts foldLeft(None)((a,io) => a match { case None => io; case Some
(i) => a})
                                 ^

不确定我做错了什么.也可能有一种方法可以使用高阶函数来更简单地做到这一点,但此处a> 引起了我的注意.

Not sure what I'm doing wrong. Also there is probably a way to do this simpler using a higher order function but nothing from here caught my eye.

推荐答案

也许这可以解决你的问题——第一个元素:

Maybe this can solve your problem - the first element:

opts.flatten.headOption

最后一个元素:

opts.flatten.lastOption

flatten 方法将取消装箱列表中的所有 Option 值并删除所有 None 值.headOption/lastOption 将返回列表中第一个/最后一个元素的 SomeNone 如果列表为空.

flatten method will unbox all Option values in the list and drop all None values. headOption/lastOption will return either Some for the first/last element in the list or None if list is empty.

这篇关于折叠选项列表以查找第一个或最后一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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