Ocaml function application operator does not work

I am trying to learn ocaml, but ran into a problem with the function link operator | >.

utop # #require "core";;
utop # open Core;;
utop # Option.value_exn(Some(1));;
- : int = 1
utop # Some(1) |> Option.value_exn;;
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

I thoght x |> fshould have been equivalent f(x). Why does it work Option.value_exn(Some(1)), but not Some(1) |> Option.value_exn?

+4
source share
2 answers

Difficulties with type inferences and optional / tagged arguments are described in the Ocaml manual . It mentions that the correct way to solve the problem is to give an explicit type indication for the nasty argument, in this case Option.value_exn. Really

Some(1) |> (Option.value_exn : int option -> int);;

works. The manual further explains that

, , - , , , , None

, Option.value_exn . , , ,

let f ?(message = "") x = x in 1 |> f;;

.

+3

, . |> :

utop # let (|>) a f = f a;;
val ( |> ) : 'a -> ('a -> 'b) -> 'b = <fun>

, 'a 'a -> 'b.

Option.value_exn 'a -> 'b - :

utop # Option.value_exn;;
- : ?here:Lexing.position ->
    ?error:Base.Error.t -> ?message:string -> 'a option -> 'a

( )

utop # Some 1 |> Option.value_exn ~here:Lexing.dummy_pos ~error:(Error.of_string "dummy") ~message:"dummy";;
- : int = 1

or just use lambda to wrap it

utop # Some 1 |> fun x -> Option.value_exn x;;
- : int = 1
+5
source

Source: https://habr.com/ru/post/1690126/


All Articles