我试图在无类型的Racket中模仿OCaml中的递归类型,但我似乎无法找到有关定义递归结构的文档。我将如何绘制这个:
type example =
| Red
| Blue of example
| Yellow of example * example;;
进入Racket的某些东西?
我尝试了以下内容:
(struct Red ())
(struct Blue (e1))
(struct Yellow (e1 e2))
(struct example/c
(or/c (Red)
(Blue example/c)
(Yellow example/c example/c)))
但是,当我将example / c放入合同时,它没有按预期工作,因为它声称它是一个程序。有什么帮助吗?
答案 0 :(得分:2)
我改变了这个例子。
以下是变量e
具有合约example/c
。
#lang racket
(struct Red () #:transparent)
(struct Blue (e1) #:transparent)
(struct Yellow (e1 e2) #:transparent)
(define example/c
(flat-murec-contract ([red/c (struct/c Red)]
[blue/c (struct/c Blue example/c)]
[yellow/c (struct/c Yellow example/c example/c)]
[example/c (or/c red/c blue/c yellow/c)])
example/c))
(define r (Red))
(define b (Blue r))
(define y (Yellow r b))
(define e y)
(provide (contract-out [e example/c]))
(match e
[(Red) (list "Red")]
[(Blue e1) (list "Blue" e1)]
[(Yellow e1 e2) (list "Yellow" e1 e2)]
[else "huh"])
如果您将(Yellow r b)
更改为(Yellow r 42)
,则会收到错误。