[racket] Traits and private data

From: Matthew Flatt (mflatt at cs.utah.edu)
Date: Wed Dec 29 15:42:28 EST 2010

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))))



Posted on the users mailing list.