Foo of int

问题描述 投票:5回答:3

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

type foo =
  | Foo of int
  | Bar of int

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

是否有任何函数的简写 foobar? 我想把一个构造函数作为函数传入,但写起来似乎很笨重 fun x -> Bar x.

ocaml
3个回答
5
投票

.增加 后缀在类型定义处,如。with variants然后用Fieldslib的语法扩展编译它。它自动生成

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
投票

您现在可以使用 ppx_variants_conv

,像这样。with fields

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

foo

© www.soinside.com 2019 - 2024. All rights reserved.