gpt4 book ai didi

ocaml - 如何在 OCAML 中使用 List.Map 跳过一个术语?

转载 作者:行者123 更新时间:2023-12-02 00:40:14 24 4
gpt4 key购买 nike

假设我有一些这样的代码:

List.map (fun e -> if (e <> 1) then e + 1 else (*add nothing to the list*))

有办法做到这一点吗?如果是这样,怎么办?

我想在项目符合某些条件时对其进行操作,如果不符合则忽略它。因此 List.filter 似乎不是解决方案。

最佳答案

SML 有一个函数 mapPartial 正是执行此操作。遗憾的是 OCaml 中不存在这个函数。但是您可以轻松地自己定义它,如下所示:

let map_partial f xs =
let prepend_option x xs = match x with
| None -> xs
| Some x -> x :: xs in
List.rev (List.fold_left (fun acc x -> prepend_option (f x) acc) [] xs)

用法:

map_partial (fun x -> if x <> 1 then Some (x+1) else None) [0;1;2;3]

将返回[1;3;4]

或者您可以使用filter_map from extlib正如 ygrek 指出的那样。

关于ocaml - 如何在 OCAML 中使用 List.Map 跳过一个术语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3202065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com