【问题标题】:Can you use a function with optional arguments for pipelining in OCaml?你可以使用带有可选参数的函数在 OCaml 中进行流水线操作吗?
【发布时间】:2020-04-01 15:53:25
【问题描述】:

我试试这个(使用核心):

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

但是解释器说:

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

这里的“这个表达式”指的是Option.value_exn

难道不能使用像value_exn 这样的函数,它具有默认值的命名参数,在单个非命名参数中进行流水线操作,而无需手动指定所有命名参数?

【问题讨论】:

    标签: ocaml default-value named-parameters


    【解决方案1】:

    诀窍是使用ppx_pipebang

    这会将f |> g 转换为g (f) 并使您的表达式编译。它还允许您在管道中使用构造函数,即使它们不是函数,例如

    x |> Some
    

    如果您要使用大量核心,我建议您使用所有 ppx_jane 来获得其他东西,例如各种 [@deriving ...] 转换,这些转换可为您免费提供核心中函子所需的许多功能。

    如果您使用dune 来构建您的项目(我相信这是现在新项目的标准),您可以将其添加到您的dune 文件中(直接取自dune 的文档):

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

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 2018-10-13
      相关资源
      最近更新 更多