将选项类型列表缩减为仅非元素的最佳方式? [英] Best way to condense a list of option type down to only elements that are not none?
本文介绍了将选项类型列表缩减为仅非元素的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我出乎意料地从一个选项列表中删除了一个列表,这个列表只包含了一些元素。
我的初始尝试是:
let ga = List.filter(fun xx - >
match xx with
| Some(g) - > true
| None - > false)gao
但是,当然,这个结果类型仍然是一个选项列表。我不知道如何使用List.map来压缩这个,因为你必须处理匹配语句中的所有情况。丑陋的:
let rec gOptRemove gdec gacc =
匹配gdec和
| head :: tail - >
与
|匹配头部一些(a) - > gOptRemove tail(a :: gacc)
|无 - > gOptRemove tail gacc
| [] - > gacc
我宁愿找到一个非递归解决方案或找出标准方法是什么
解决方案
简单地
List.choose id
如
> [有些4;没有;一些2;无] |> List.choose id ;;
val it:int list = [4; 2]
I'm unexpectedly having a bit of trouble with going from a list of 'a option down to a list containing only the elements that are Some.
My initial attempt was:
let ga = List.filter (fun xx ->
match xx with
| Some(g) -> true
| None -> false) gao
But of course, this result type is still 'a option list. I don't know how to use List.map to condense this, because you have to handle all cases in a match statement. I have an ugly solution, but I'm wondering if there is something better.
Ugly:
let rec gOptRemove gdec gacc =
match gdec with
| head :: tail ->
match head with
| Some(a) -> gOptRemove tail (a :: gacc)
| None -> gOptRemove tail gacc
| [] -> gacc
I would prefer to find a non-recursive solution or find out what the standard way is for this kind of thing.
解决方案
Simply
List.choose id
as in
> [Some 4; None; Some 2; None] |> List.choose id;;
val it : int list = [4; 2]
这篇关于将选项类型列表缩减为仅非元素的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文