斯卡拉首先在列表中返回一些 [英] scala return on first Some in list

查看:132
本文介绍了斯卡拉首先在列表中返回一些的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表 l:列表[T1] ,目前正在执行以下操作:

I have a list l:List[T1] and currently im doing the following:

myfun : T1 -> Option[T2]
val x: Option[T2] = l.map{ myfun(l) }.flatten.find(_=>true)

myfun 函数返回None或Some,flatten会抛出所有None,并返回第一个元素列出如果有的话。

The myfun function returns None or Some, flatten throws away all the None's and find returns the first element of the list if any.

这对我来说似乎有点不好意思。我认为可能存在一些理解或类似的东西,这样做会减少浪费或更聪明。
例如:如果 myfun 返回任何 某些在 l 列表的地图

This seems a bit hacky to me. Im thinking that there might exist some for-comprehension or similar that will do this a bit less wasteful or more clever. For example: I dont need any subsequent answers if myfun returns any Some during the map of the list l.

推荐答案

如何:

How about:

l.toStream flatMap (myfun andThen (_.toList)) headOption

流是懒惰的,所以它不会预先映射所有的东西,但它不会重新映射事情要么。将选项转换为 List ,使 flatMap >可以使用。

Stream is lazy, so it won't map everything in advance, but it won't remap things either. Instead of flattening things, convert Option to List so that flatMap can be used.

这篇关于斯卡拉首先在列表中返回一些的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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