[英]How do I define a recursive struct in Racket?
我正在尝试在无类型 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 放入合同时,它并没有按预期工作,因为它声称这是一个程序。 有什么帮助吗?
我已经改变了这个例子。 这是一个示例,其中变量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 rb)
更改为(Yellow r 42)
则会出现错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.