我经常发现自己在构造函数作为参数传递给
|>
等方法时使用 List.find
运算符。例如,我有这个代码片段:
let parse_test_header (header : string list) : string * (string list) =
let is_attr (line : string) : bool = ':' == get line 0 in
let test_name = List.find (fun line -> line |> is_attr |> not) header in
let test_attrs = List.filter is_attr header in
(test_name, test_attrs)
为了简单起见,我想使用
|>
而不必先将其包装在 fun ... -> ...
中,例如:
let parse_test_header (header : string list) : string * (string list) =
let is_attr (line : string) : bool = ':' == get line 0 in
let test_name = List.find (is_attr |> not) header in
let test_attrs = List.filter is_attr header in
(test_name, test_attrs)
但是,这给出了
31 | let test_name = List.find (is_attr |> not) header in
^^^^^^^
Error: This expression has type string -> bool
but an expression was expected of type bool
有什么办法可以做到这一点吗?
考虑
|>
是如何实现的:
let ( |> ) x f = f x
您将
is_attr
作为第一个参数传递,它是一个函数,这意味着 not
需要将函数作为其参数。它不会导致类型不匹配。
您正在寻找函数composition,由于值限制,该函数可能很棘手,但可以实现。我们称这个运算符为
|>
。
let ( |. ) f g x = g (f x)