构造函数的简写

Nat*_*ote 5 ocaml

有没有办法将构造函数作为函数传递?

type foo =
  | Foo of int
  | Bar of int

let foo x = Foo x
let bar = fun x -> Bar x
Run Code Online (Sandbox Code Playgroud)

是否有功能的任何速记foobar?我想将构造函数作为函数传递,但编写起来似乎不实用fun x -> Bar x.

Vir*_*ile 5

camlspotter的答案足够接近,但在你的情况下,你想使用Variantslibwith variants在你的类型定义的末尾添加:

type foo = Foo of int | Bar of int with variants;;
Run Code Online (Sandbox Code Playgroud)

为您提供以下内容:

type foo = Foo of int | Bar of int
val bar : int -> foo = <fun>
val foo : int -> foo = <fun>                                                    
module Variants :
  sig
    val bar : (int -> foo) Variantslib.Variant.t
    val foo : (int -> foo) Variantslib.Variant.t
  end
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的回答。我很失望我需要下载一个第三方库来做到这一点,尽管我印象深刻的是向语言添加语法特征相对简单。 (2认同)