有什么办法将构造函数作为函数传递吗?构造函数的速记
type foo =
| Foo of int
| Bar of int
let foo x = Foo x
let bar = fun x -> Bar x
是否有功能foo
和bar
任何速记?我想传递一个构造函数作为函数,但编写fun x -> Bar x
似乎很笨拙。
有什么办法将构造函数作为函数传递吗?构造函数的速记
type foo =
| Foo of int
| Bar of int
let foo x = Foo x
let bar = fun x -> Bar x
是否有功能foo
和bar
任何速记?我想传递一个构造函数作为函数,但编写fun x -> Bar x
似乎很笨拙。
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
使用Fieldslib:https://github.com/janestreet/fieldslib。
在喜欢的类型定义添加with fields
后缀:
type foo = | Foo of int | Bar of int with fields
,并与Fieldslib的语法扩展编译。它会自动为您生成foo
和bar
。
Fieldslib是记录,而不是和类型。它会在'type foo = {foo:int; bar:int} with fields',但不是实际的例子。 – Virgile
哦,对不起。然后你需要类似的P4扩展到Fieldslib,但是需要变体。 – camlspotter
感谢您的回答。我很失望,我需要下载第三方库才能做到这一点,但我留下深刻印象的是,为语言添加语法功能相对简单。 –