Søren Debois
Søren Debois

Reputation: 5688

Can you use a function with optional arguments for pipelining in OCaml?

I try this (using Core):

    Some 9 
      |> Option.value_exn 
      |> printf "%d\n"

But the interpreter says:

Line 2, characters 9-25:
Error: This expression has type
         ?here:Base__Source_code_position0.t ->
         ?error:Base.Error.t -> ?message:string -> 'a option -> 'a
       but an expression was expected of type int option -> 'b

"This expression" here refers to Option.value_exn.

Is it impossible to use a function like value_exn that has named parameter with default values, pipelining in the single non-named parameter, without manually specifying all the named parameters?

Upvotes: 0

Views: 244

Answers (1)

Dan Robertson
Dan Robertson

Reputation: 4360

The trick is to use ppx_pipebang

This will transform f |> g into g (f) and make your expression compile. It also allows you to use constructors in a pipeline even though they are not functions, e.g.

x |> Some

If you’re going to use a lot of core, I would recommend using all of ppx_jane to get other things like various [@deriving ...] transformations which give you for free many functions required by functors in Core.

If you are using dune to build your project (I believe this is now the standard for new projects), you can add this to your dune file (taken straight from the documentation of dune):

(executable
 (name hello_world)
 (libraries core)
 (preprocess (pps ppx_jane)))

Upvotes: 2

Related Questions