是否有一种将元组列表转换为列表的方式比我所做的要多?
我的目标是将(int * int)列表
转换为int List
。这就是我所做的:
let tuples_list_to_list l =
let rec aux_tuples_to_list acc l =
match l with
| [] -> acc
| x :: tl -> aux_tuples_to_list (fst x :: snd x :: acc) tl in
aux_tuples_to_list [] l
我想知道是否有一个更“优雅”的,即使这是主观的或至少更好的写我功能的方法。我正在考虑使用list.map
或list.fold_left
,但是我在弄清楚我可以使用这两个功能来完成我所做的事情。基本上,我认为有可能拥有一个单线,而不是我写的整个功能。
你怎么认为?谢谢
My goal here was to convert a (int * int) list
to an int list
. This is what I did:
let tuples_list_to_list l =
let rec aux_tuples_to_list acc l =
match l with
| [] -> acc
| x :: tl -> aux_tuples_to_list (fst x :: snd x :: acc) tl in
aux_tuples_to_list [] l
I was wondering if there was a more "elegant" even though this is subjective or at least better, way to write my function. I was thinking about using List.map
or List.fold_left
but I was having issues figuring out I could use those two functions to do the same thing I did. Basically, I think it would be possible to have a one-liner instead of the whole function I wrote.
What do you think? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此任务适用于
list.concat_map
(在其他某些语言中也称为“平面地图”):您可以使用
list.fold_left
,但是您必须反向最后的结果随着列表的相反顺序构建:This task is suited for
List.concat_map
(also known as "flat map" in some other languages):You can use
List.fold_left
, but you'll have to reverse the result at the end as the list is constructed in reverse order:您还可以在模式匹配中解构元组值,而不是使用
fst
和snd
(此版本,与您的不同,给出了一个结果列表,其数字的数字与数字一样orignal):另一个选项是使用
list.fold_right
,它避免了在末尾以不为尾部递归的成本倒转累加器列表的需要:You can also deconstruct the tuple values in the pattern matching instead of using
fst
andsnd
(This version, unlike yours, gives a result list with the numbers in the same order as the orignal):Yet Another Option is using
List.fold_right
, which avoids the need to reverse the accumulator list at the end at the cost of not being tail recursive: