[racket] Scheme Design Patterns

From: Jay McCarthy (jay.mccarthy at gmail.com)
Date: Tue Sep 10 09:16:34 EDT 2013

I think more context would be useful to know why a specific case is useful.
But, I'll do my best with none...

By using functions like this, you can control when things happen and what
they can see. For instance...

(define (make-worker)
  (define a (build-list 10 add1)
  (define (worker)
    ;; a is visible to 'worker'
    (+ (first a) 10))
  worker)

;; a is not visible here

;; .... you do some other work ...

;; and only now do you run the construction of a

(define some-worker
  (make-worker))

;; .... you do some other work before getting the contents

(define answer
  (some-worker))

This is all because closures are a basic form of objects---their
environment values are their "private fields" and "apply" is their one
method. Thus, any time that you would find OO useful, you might find a
pattern like this useful. Especially when you don't want to go whole hog
and use the object/class system from racket/class

Jay




On Mon, Sep 9, 2013 at 8:24 PM, Chad A. <chad at neomantic.com> wrote:

> Hi,
>
> I'm wondering if someone can help me understand a design-pattern that
> I have noticed in the Racket code base. (I'm teaching myself, so
> review other people's code alot).
>
> I've seen this pattern..which is a bit contrived.
>
> (define (say-hello)
>   (define (display-hello)
>      (display "hello")))
>
> So this produces a producer, and to evaluate it I would need to write
> ((hello)) => "hello"
>
> But then I see this...
>
> (define say-hi (say-hello)).  When I evaluate (say-hello), I get
> "hello".  Obviously, the definition of "say-hi" contains the evaluated
> (say-hello) than returns the 'display-hello' procedure to be
> evaluated.
>
> My question is...why would I want to write the code like this? 3
> definitions have been created which could easily be compressed into
> one.
>
>  (I also see nothing in the code I'm looking at that appears to
> capture a binding via a closure).
>
> Thanks in advance for any insights someone can share.
>
> Chad
> ____________________
>   Racket Users list:
>   http://lists.racket-lang.org/users
>



-- 
Jay McCarthy <jay at cs.byu.edu>
Assistant Professor / Brigham Young University
http://faculty.cs.byu.edu/~jay

"The glory of God is Intelligence" - D&C 93
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20130910/ce9c8f63/attachment.html>

Posted on the users mailing list.