Frage

Is there any way to pass a constructor as a function?

type foo =
  | Foo of int
  | Bar of int

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

Is there any shorthand for the functions foo and bar? I want to pass a constructor as a function, but it seems unwieldy to write fun x -> Bar x.

War es hilfreich?

Lösung

camlspotter's answer was close enough, but in your case you want to use Variantslib and add with variants at the end of your type definition:

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

gives you the following:

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

Andere Tipps

Use Fieldslib: https://github.com/janestreet/fieldslib .

Adding with fields postfix at the type definition like:

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

and compile it with Fieldslib's syntax extension. It automatically generates foo and bar for you.

You can now use ppx_variants_conv, like this:

type 'a t =
  | A of 'a
  | B of char
  | C
  | D of int * int
  [@@deriving variants]
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top