[racket] struct constructor pitfalls

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Wed May 29 17:54:34 EDT 2013

On May 29, 2013, at 3:12 PM, Anthony Carrico <acarrico at memebeam.org> wrote:

> It seems like the purpose of #:constructor-name is to get the default
> contsructor out of the way,

It's really just to move from make-hello to hello for constructor names w/ easy backward compatibility. 

> so you can customize it:
> #lang racket
> (struct hello (a b c)
>  #:constructor-name hello-rep
>  )
> (define (hello) (hello-rep 1 2 3))

If you want to have constructors and/or selectors and/or mutators that aren't standard, you may wish to use this pattern: 

(define-values (constructor predicate selector)
  (let ()
    (struct my (you))
    (values my my? (lambda (x) (displayln `(accessing the ,x struct)) (my-you x)))))

But yes, this eliminates other things you may have. 

-- Matthias

> But this gives the error:
>  duplicate definition for identifier in: hello
> Work arounds:
> 1. Use a guard, but this restricts the signature of the constructor.
> 2. Use a module to manage the names, but this is annoying.
> 3. Fall back on the make-hello convention instead of using the
>    struct's name to construct it.
> This is particularly painful if you have code that already uses a
> default constructor name. You may want to change the struct's
> representation, but now you can't emulate the old constructor. I guess
> the forward looking programmer would always use the make-xxx convention
> to avoid this pitfall. Am I missing anything?
> -- 
> Anthony Carrico
> ____________________
>  Racket Users list:
>  http://lists.racket-lang.org/users

Posted on the users mailing list.