【发布时间】:2018-11-10 02:56:12
【问题描述】:
假设我想在 OCaml 中建模一个简单的表达式类型:
type expr =
| `Int of int
| `Str of string
| `IntAdd of expr * expr
| `StrAdd of expr * expr
是否可以将expr * expr 中的expr 限制为expr 本身的特定构造函数(即我希望IntExpr 只允许'Int')?我可以用模式模仿这个
匹配,但在 expr 扩展后变得很麻烦。我能以某种方式
使用OCaml的类型系统来实现这个?
我尝试使用多态类型上限如下:
type expr =
| `Int of int
| `Str of string
| `IntAdd of [< `Int] * [< `Int]
| `StrAdd of [< `Str] * [< `Str]
但是编译器不接受这个(带有消息In case IntAdd of [< Int ] * ([< Int ] as 'a) the variable 'a is unbound)。有什么诀窍可以使这项工作发挥作用吗?
【问题讨论】:
-
这似乎是您在 Haskell 中使用 GADT 的那种事情:
data Expr a where { Int :: Int -> Expr Int; Str :: String -> Expr String; IntAdd :: Expr Int -> Expr Int -> Expr Int; StrAdd :: Expr String -> Expr String -> Expr String } -
最后一个链接真的很有帮助---谢谢!
标签: types ocaml polymorphic-variants