我如何在Ocaml中编写二进制多态变体?

问题描述 投票:0回答:1

考虑一种类型,例如:

type maybe_int = Just of int | Nothing  

utop # Just 1;;  
- : maybe_int = Just 1  

它是sum type int + 1。可以很容易地将其概括为∀a,a + 1

type 'a maybe = Just of 'a | Nothing  

utop # Just 1;;  
- : int maybe = Just 1  

utop # Just "Meow!";;  
- : string maybe = Just "Meow!"  

现在考虑类型int +字符串

type either_int_string = Left of int | Right of string  

对应的多态总和∀a b,a + b可能写为:

type 'a 'b either = Left of a | Right of b  

—但是,这是语法错误。

根据这种观察,如何获得多态代数数据类型?

polymorphism ocaml algebraic-data-types parametric-polymorphism union-types
1个回答
0
投票

使用元组指定多个类型变量:

type ('a, 'b) either = Left of 'a | Right of 'b

您还缺少右侧的撇号。

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