| title | Pipe First |
|---|
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
|. bara
->foo(b)
->baris equal to
bar(foo a b)bar(foo(a, b))JavaScript's APIs are often attached to objects, and often chainable, like so:
constresult=[1,2,3].map(a=>a+1).filter(a=>a%2===0);asyncRequest().setWaitDuration(4000).send();Assuming we don't need the chaining behavior above, we'd bind to each case this using bs.send from the previous section:
externalmap : 'aarray -> ('a -> 'b) -> 'barray="map" [@@bs.send]
externalfilter : 'aarray -> ('a -> 'b) -> 'barray="filter" [@@bs.send]
typerequestexternalasyncRequest: unit -> request="asyncRequest"externalsetWaitDuration: request -> int -> request="setWaitDuration" [@@bs.send]
externalsend: request -> unit="send" [@@bs.send][@bs.send] externalmap: (array('a),'a => 'b) => array('b) ="map";
[@bs.send] externalfilter: (array('a),'a => 'b) => array('b) ="filter";typerequest;externalasyncRequest:unit => request="asyncRequest";
[@bs.send] externalsetWaitDuration: (request,int) => request="setWaitDuration";
[@bs.send] externalsend:request => unit="send";You'd use them like this:
let result = filter (map [|1; 2; 3|] (funa -> a +1)) (funa -> a mod2=0)
let()= send(setWaitDuration (asyncRequest()) 4000)letresult= filter(map([|1,2,3|], a => a +1), a => a mod2==0);
send(setWaitDuration(asyncRequest(),4000));This looks much worse than the JS counterpart! Now we need to read the actual logic "inside-out". We also cannot use the |> operator here, since the object comes first in the binding. But |. and -> work!
let result = [|1; 2; 3|]
|. map(funa -> a +1)
|. filter(funa -> a mod2==0)
let()= asyncRequest ()|. setWaitDuration 400|. sendletresult=[|1,2,3|]->map(a => a +1)
->filter(a => a mod2===0);
asyncRequest()->setWaitDuration(400)->send;This works:
let result = name |. preprocess |.Someletresult= name->preprocess->SomeWe turn this into:
let result =Some(preprocess(name))letresult=Some(preprocess(name))