[racket] Traits and private data
On Wed, 2010-12-29 at 13:42 -0700, Matthew Flatt wrote:
> At Wed, 29 Dec 2010 19:23:24 +0200, Markku Rontu wrote:
> > Now what would be closer to my wishes is something like this where the
> > counter is protected and not exposed.
> >
> > ---
> >
> > (define protected-counted-trait
> > (trait
> > (define counter 0)
> >
> > (define/public (add!)
> > (set! counter (add1 counter)))
> >
> > (define/public (current-count)
> > counter)))
> >
> > ---
> >
> > This however is not possible as far as I know. There is a hint to some
> > solution in the Racket Reference 5.6 Traits:
> >
> > "External identifiers in trait, trait-exclude, trait-exclude-field,
> > trait-alias, trait-rename, and trait-rename-field forms are subject to
> > binding via define-member-name and define-local-member-name. Although
> > private methods or fields are not allowed in a trait form, they can be
> > simulated by using a public or field declaration and a name whose scope
> > is limited to the trait form."
>
> Like this:
>
> (define protected-counted-trait
> (let ()
> (define-local-member-name counter)
>
> (trait
> (field (counter 0))
>
> (define/public (add!)
> (set! counter (add1 counter)))
>
> (define/public (current-count)
> counter))))
>
Thanks!
That does the trick. I wrote a macro to have a "trait/private" that
introduces "field/private" which does the magic behind the scenes.
-Markku