gpt4 book ai didi

Ocaml 函数应用运算符失败

转载 作者:行者123 更新时间:2023-12-04 23:14:04 27 4
gpt4 key购买 nike

我正在尝试学习 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_exn(Some(1))工作但不工作 Some(1) |> Option.value_exn ?

最佳答案

不,它们不是等价的。您可以定义 |>运营商为:

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

或者只是使用 lambda 来包装它
utop # Some 1 |> fun x -> Option.value_exn x;;
- : int = 1

关于Ocaml 函数应用运算符失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47592676/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com