列表过滤器,然后在 OCaml 中列出地图



如何在 OCaml 中的列表映射之前应用列表过滤器?我正在尝试管道操作员,但没有成功:

let r infile =
match List.tl (In_channel.read_lines infile ) with
| None -> []
| Some body ->
List.filter body ~f:(fun line -> true)
|> List.map body ~f:(fun line ->
match split_on_comma line with
| _ :: _ :: num :: street :: unit :: city :: _ :: region :: _ ->
String.strip (num ^ " " ^ addr_case street ^ ", " ^ addr_case city ^ " " ^ region)
| _ -> assert false)

Utop给我:

"此表达式具有类型字符串列表 但是需要字符串列表 -> 'a' 类型的表达式

我知道List.filter目前什么都不做。我只是想在List.map之前使用它

标准的 OCaml List.filter 没有~f:参数。很可能您正在使用 Core。

我现在没有设置核心,所以我无法测试。但一个可能的问题是您在List.map调用中使用body。我认为你应该把它排除在外。您想要处理List.filter表达式的结果。您不想处理 body,这是匹配项的原始值。

下面是一个使用 OCaml 标准库版本的函数的类似表达式:

# ListLabels.filter [1; 2; 3; 4]
~f: (fun x -> x mod 2 = 0) |>
ListLabels.map ~f: (fun x -> x + 10) ;;
- : int list = [12; 14]

最新更新