Rescript/ReasonML like "->" operator (or chain to first position)

Being new to Ocaml I love the “|>” operator. Love the way we can chain things. However for this to work, the thing being chained should be the last parameter of the function being called next let (|>) x f = f x However sometimes the APIs are designed in a way where the collection is not the last parameter. Good example of this is Hashbtl. I cannot write code like x |> Hashtbl.find_opt 10" because the find_opt API is written as ('a, 'b) Hashtbl.t -> 'a -> 'b option and not 'a -> 'b option -> ('a, 'b) Hashtbl.t

So how to chain when the thing being chained is the first parameter and not the last one?

1 Like

Once upon a time there was ppx_fast_pipe but it seems to have fallen out of date.

1 Like

You could always write:

table
|> (fun x -> Hashtbh.find_opt x "10")

It’s a bit more code, but allows you to express a computation as chaining regardless of the parameter order.

3 Likes

For functions on collections like Hashtbl, the arguments aren’t arranged to enable |> chaining because they return unit anyway. In these cases it is clearer to just apply the function normally (or with @@), and sequence with the ; operator.

4 Likes

It’s a bit more code, but allows you to express a computation as chaining regardless of the parameter order.

Yes makes sense. much better than hand rolling my own custom operator.

Yes, I would be curious to see what Hashtbl code would benefit from using a pipe operator in the first place. In an immutable map, it’s nice to be able to write add key1 val1 map |> add key2 val2 |> add key3 val3 |> ...etc but that doesn’t make sense when your add function returns unit.

If you’re looking for a nicer syntax for working with “t-first” mutable collections, then using extended indexing operators is one option that’s designed for them.

i think the tap combinator from the lovely containers lib can give what you’d like here!

1 Like

Sometime, when 2 arguments should be swapped, Fun.flip can help.

2 Likes