Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ocaml函数应用程序运算符失败_Ocaml - Fatal编程技术网

Ocaml函数应用程序运算符失败

Ocaml函数应用程序运算符失败,ocaml,Ocaml,我试图学习ocaml,但遇到了函数组合运算符|>的问题 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 ->

我试图学习ocaml,但遇到了函数组合运算符|>的问题

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

我认为
x |>f
应该等同于
f(x)
。为什么
Option.value\u-exn(一些(1))
起作用,但
Some(1)|>Option.value\u-exn不起作用?

不,它们是不等价的。您可以将
|>
运算符定义为:

utop # let (|>) a f = f a;;
val ( |> ) : 'a -> ('a -> 'b) -> 'b = <fun>
可以显式指定所有命名参数(实际上没有意义)

或者用lambda包起来

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

中描述了类型推断和可选/标记参数的困难。它提到解决问题的正确方法是为麻烦的参数提供显式的类型归属,在本例中为
Option.value\u exn
。确实如此

Some(1) |> (Option.value_exn : int option -> int);;
工作。手册进一步解释了这一点

在特定情况下,如果预期类型是未标记的函数类型,而参数是预期可选参数的函数,编译器将尝试转换参数,使其与预期类型匹配,方法是为所有可选参数传递None

但是,
Option.value\u exn
的多态性似乎干扰了这种机制。有证据表明,正是多元主义导致了这一问题,这一点可以从金融危机的失败中看出

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

出于同样的原因。

看起来可选参数
?here
?error
?message
正在妨碍您。你可能想试试
Some(1)|>funx->Option.value\uexnx1 |>f
let f?(b=0)a=a+b
?@rymdhund这是因为b在这里是一个可选参数,所以不必给它赋值。这与必须给定值的命名参数不同
Some(1) |> (Option.value_exn : int option -> int);;
let f ?(message = "") x = x in 1 |> f;;