ocaml-取消可选列表:有没有更简单的方法? [英] ocaml - deoptionalize a list: is there a simpler way?

查看:85
本文介绍了ocaml-取消可选列表:有没有更简单的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个函数来取消整数列表的可选操作,我想知道是否有更好的写方法.

I have written a function to deoptionalize an integer list and I would like to know if there is a better way to write it.

let deoptionalize (lst:'a option list) : 'a list =
    List.map ~f:(fun x -> match x with Some x -> x | None -> assert false)
                    (List.filter ~f:(fun x -> x <> None) lst)
;;

在作业中,我目前正在使用地图,必须使用过滤器.

In the assignment I am currently working its using map and filter is a must.

推荐答案

我认为手动编码"解决方案(即没有mapfilter的)更易于阅读,但是如果您确实需要使用他们,你去了:

I suppose that a "hand-coded" solution (i.e. without map and filter) is easier to read, but if you really need to use them, here you go:

似乎您正在使用Core库.如果是这样,我认为您的解决方案还不错,但是可以写得更紧凑一些:

It seems that you are using the Core library. If so, I think your solution is not so bad, but can be written a bit more compact:

let deoptionalize lst = 
    List.filter ~f:(is_some) lst
    |> List.map ~f:(function | Some x -> x | None -> assert false)

如果您不介意警告(我不鼓励您这样做),您甚至可以省略其他内容:

If you don't mind warnings (which I discourage you to do), you can even leave out some more:

let deoptionalize lst = 
    List.filter ~f:(is_some) lst
    |> List.map ~f:(fun (Some x) -> x)

实际上,Core提供了将两者结合的filter_map(感谢@Ramon Snir作为提示),因此您可以使用:

Actually, Core provides filter_map (thanks @Ramon Snir for the hint) which combines both, so you can use:

let deopt lst = 
    List.filter_map ~f:(fun x -> x) lst;;

这篇关于ocaml-取消可选列表:有没有更简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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