构造函数的简写

时间:2014-04-17 07:43:41

标签: ocaml

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

type foo =
  | Foo of int
  | Bar of int

let foo x = Foo x
let bar = fun x -> Bar x

是否有foobar函数的简写?我想将构造函数作为函数传递,但写fun x -> Bar x似乎很笨拙。

3 个答案:

答案 0 :(得分:5)

camlspotter的回答非常接近,但在您的情况下,您希望使用Variantslib并在类型定义的末尾添加with variants

type foo = Foo of int | Bar of int with variants;;

为您提供以下内容:

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

答案 1 :(得分:1)

使用Fieldslib:https://github.com/janestreet/fieldslib

在类型定义中添加with fields后缀,如:

type foo = | Foo of int | Bar of int with fields

并使用Fieldslib的语法扩展编译它。它会自动为您生成foobar

答案 2 :(得分:0)

您现在可以使用ppx_variants_conv,如下所示:

type 'a t =
  | A of 'a
  | B of char
  | C
  | D of int * int
  [@@deriving variants]