Fast Pipe
BuckleScript has a special |.
(or ->
for Reason) pipe syntax for dealing with various situations. This operator has many uses.
管道线
The pipe takes the item on the left and put it as the first argument of the item on the right. Great for building pipelines of data processing:
a
|. foo b
|. bar
a
->foo(b)
->bar
等价于
bar(foo a b)
bar(foo(a, b))
Js 链式操作
JavaScript 的 api 通常附加到对象, 并且经常是可链式操作的, 如下所示:
const result = [1, 2, 3].map(a => a + 1).filter(a => a % 2 === 0);
asyncRequest().setWaitDuration(4000).send();
假设我们不需要上面的链接行为, 我们需要通过前面章节介绍过的 bs. send
进行绑定。
external map : 'a array -> ('a -> 'b) -> 'b array = "" [@@bs.send]
external filter : 'a array -> ('a -> 'b) -> 'b array = "" [@@bs.send]
type request
external asyncRequest: unit -> request = ""
external setWaitDuration: request -> int -> request = "" [@@bs.send]
external send: request -> unit = "" [@@bs.send]
[@bs.send] external map : (array('a), 'a => 'b) => array('b) = "";
[@bs.send] external filter : (array('a), 'a => 'b) => array('b) = "";
type request;
external asyncRequest: unit => request = "";
[@bs.send] external setWaitDuration: (request, int) => request = "";
[@bs.send] external send: request => unit = "";
你将这样使用:
let result = filter (map [|1; 2; 3|] (fun a -> a + 1)) (fun a -> a mod 2 = 0)
let () = send(setWaitDuration (asyncRequest()) 4000)
let result = filter(map([|1, 2, 3|], a => a + 1), a => a mod 2 == 0);
send(setWaitDuration(asyncRequest(), 4000));
这比JS版本的差很多! 现在我们需要阅读它实际的逻辑 "inside-out"。 我们也不能使用 |>
运算符, 因为在绑定中对象优先。 But |.
and ->
work!
let result = [|1; 2; 3|]
|. map(fun a -> a + 1)
|. filter(fun a -> a mod 2 == 0)
let () = asyncRequest () |. setWaitDuration 400 |. send
let result = [|1, 2, 3|]
->map(a => a + 1)
->filter(a => a mod 2 === 0);
asyncRequest()->setWaitDuration(400)->send;
变体管道
这样是可以的:
let result = name |. preprocess |. Some
let result = name->preprocess->Some
我们把它变成:
let result = Some(preprocess(name))
let result = Some(preprocess(name))