Saturday, December 7, 2013

Pipelining with the |> operator in OCaml

Pipelining with |> in OCaml

Reading through Real World OCaml (which I'm really enjoying and can heartily recommend by the way), I came across this clever definition for pipe notation.
let ( |> ) x f = f x
This little operator allows for (maybe misusing a term I think may have been coined by my friend MS,) "reverse application". To get a sense of the impact on readability that it may have, I applied it to the program of this earlier blog entry. At the heart of the program is the following little fragment.
match (filesin !root) with
| Some names ->
  let n=String.length !suffix in
  let pred e =
    let i = (String.length e - n) in
    (i >= 0) && (String.sub e i n) = !suffix
  in process_files (List.filter pred (Array.to_list names) )
Now, rewritten to use pipelining by virtue of |> we get this.
match (filesin !root) with
| Some names ->
  let n=String.length !suffix in
  let pred e =
    let i = (String.length e - n) in
    (i >= 0) && (String.sub e i n) = !suffix
  in names |> Array.to_list |> List.filter pred |> process_files 
 
I might be easily amused but... wow!

Coincidentally, reading from the OCaml PRO blog I learned of this related operator (also shown independently to me by my buddy -- thanks Stefano!).
let ( @@ ) f x = f x
This one can be used to good effect reducing the syntactic noise of lots of parentheses as per their example.
List.iter print_int @@ List.map (fun x -> x + 1 ) @@ [1; 2; 3]
(I assume it's obvious what this does and also, I added spaces in accordance with this advice).

Of course, if I'd had my wits about me, I'd have realized that I've known this operator all this time as $ from the Felix programming language... No excuse man, I mean, it's right there in the introductory tutorial!
println$ "Hello " + Env::getenv "USER";
Sorry 'bout being so slow to catch on Felix!

Now, I must admit I prefer $ to @@ but careful examination of the syntax reference seems to me that it won't be appropriate for OCaml (in that $ is left associative). As a final note, |> and @@ are "builtin" operators in OCaml compilers today.