重载结构构造函数 [英] Overloading a struct constructor
问题描述
有没有办法重载 Racket 中结构的构造函数,以便我可以使继承的参数成为可选的?
Is there a way to overload the constructor for a struct in Racket, so I can make the inherited parameters optional ?
就我而言,我想为我的应用定义一些自定义异常.例如:
In my case, I want to define some custom exceptions for my app. For example :
(struct exn:my-app exn ())
(struct exn:my-app:illegal-access exn:my-app ())
但是,要实例化非法访问异常,我必须使用从 exn 继承的 2 个参数(消息和延续标记)调用构造函数,这非常麻烦.
However, to instantiate an illegal-access exception, I have to call the constructor with the 2 arguments inherited from exn (message and continuation-marks), which is quite cumbersome.
是否可以定义(对于 exn:my-app 及其所有后代)一个构造函数,它可以使两个参数都可选?所以我可以打电话给:
Is it possible to define (for exn:my-app and all its descendants) a constructor, which could make both parameters optional ? So I could call either :
(raise (exn:my-app:illegal-access))
(raise (exn:my-app:illegal-access "Message")) ?
谢谢,
推荐答案
这是一种方法:
(struct exn:my-app exn ()
;; change the name of the constructor
#:constructor-name make-exn:my-app)
;; custom constructor
(define (exn:my-app [msg "default msg"]
[marks (current-continuation-marks)])
(make-exn:my-app msg marks))
(exn:my-app) ; this works now
由于您需要为每个结构类型执行此操作,因此您可能需要定义一个宏来抽象它.我敢打赌,有人已经在 Racket 邮件列表上分享了这样的宏,但我想不起来,所以如果找到参考,我会更新这个答案.
Since you need to do this for each structure type, you may want to define a macro that abstracts over this. I bet someone has already shared such a macro on the Racket mailing list, but I don't recall one off the top of my head so I'll update this answer if I find a reference.
这篇关于重载结构构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!