2014-04-17 61 views
5

有什么办法将构造函数作为函数传递吗?构造函数的速记

type foo = 
    | Foo of int 
    | Bar of int 

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

是否有功能foobar任何速记?我想传递一个构造函数作为函数,但编写fun x -> Bar x似乎很笨拙。

回答

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

+0

Fieldslib是记录,而不是和类型。它会在'type foo = {foo:int; bar:int} with fields',但不是实际的例子。 – Virgile

+0

哦,对不起。然后你需要类似的P4扩展到Fieldslib,但是需要变体。 – camlspotter