Search code examples
ocamlconventionsreason

When to use piping |> versus arguments


In Reason (and OCaml), there is a non-traditional way of passing arguments using the |> operator. What is the convention for when it should be used? I am currently using it all over the place just because of how novel I find it.


Solution

  • Using |> (forward pipe) is helpful for showing the order of executions.

    For example, if you want to execute function f, then g like this:

    g(f(x))
    

    It's easier to see the order of executions (e.g., f and then g) this way:

    x |> f |> g
    

    Programming languages like OCaml or F# are used a lot to transform data from one form to another, so |> can be used that way to show how data got transformed.

    let sqr = x => x * x;
    
    [1,2,3]
    |> List.map (x => x + 1)
    |> List.map (sqr);