有没有办法将构造函数作为函数传递?
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)
是否有功能的任何速记foo
和bar
?我想将构造函数作为函数传递,但编写起来似乎不实用fun x -> Bar x
.
camlspotter的答案足够接近,但在你的情况下,你想使用Variantslib并with 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)