Struct constructor overload

Is there a way to overload the constructor for a structure in Racket, so I can make inherited options optional?

In my case, I want to define some custom exceptions for my application. For instance:

(struct exn:my-app exn ())
(struct exn:my-app:illegal-access exn:my-app ())

However, to create an instance of illegal access exceptions, I have to call the constructor with two arguments inherited from exn (message and continuation-tags), which is rather cumbersome.

Is it possible to define (for exn: my-app and all its descendants) a constructor that can make both parameters optional? So I could call:

(raise (exn:my-app:illegal-access))
(raise (exn:my-app:illegal-access "Message")) ?

Thank,

+2
source share
1 answer

Here is one way to do this:

(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, , , .

+4

All Articles