
Scheme: Procedures that return another inner procedure - luu
http://stackoverflow.com/questions/12496482/scheme-procedures-that-return-another-inner-procedure/12496867
======
niklasni1
This is the "closure/object isomorphism", basically.

The outer function (cons) is a class constructor. It returns an object, which
is a function of one argument, where the argument is equivalent to the name of
a method. In this case, the methods are getters, so they evaluate to values.
You could just as easily have stored more procedures in the object returned by
the constructor.

In this case, numbers where chosen as method names and sugary procedures
defined outside the object itself. You could have used symbols:

    
    
        (define (cons x y)
          (lambda (method)
            (cond ((eq? method 'car) x)
                  ((eq? method 'cdr) y)
                  (else (error "unknown method")))))
    

In which case what you have more closely resembles OO:

    
    
        # (define p (cons 1 2))
        # (p 'car)
        1
        # (p 'cdr)
        2

~~~
markc
Nice. Or you can use the procedural representation. E.g. in Clojure:

    
    
        (defn pcons [x y] (fn [m] (m x y)))
        (defn pcar [z] (z (fn [p q] p)))
        (defn pcdr [z] (z (fn [p q] q)))
    
        (pcar (pcons 2 3)) ==> 2
        (pcdr (pcons 2 3)) ==> 3

~~~
agumonkey
I still look at this, and the whole LC encoded structures, with amazement. I
love how things are mutually molded together and almost empty. Most of the LC
felt that way, accumulation of lots of nothingness that achieve something.

------
stuaxo
Ah, this is like closures or decorators in python.

~~~
junke
Those _are_ closures (btw, did you mean generators instead of decorators?).
Until nonlocal
([https://www.python.org/dev/peps/pep-3104/](https://www.python.org/dev/peps/pep-3104/)),
python closures were limited ([http://stackoverflow.com/questions/141642/what-
limitations-h...](http://stackoverflow.com/questions/141642/what-limitations-
have-closures-in-python-compared-to-language-x-closures)). Even though
nonlocal solves the problems, the resulting scoping rules are messy: global,
local, nonlocal, ...

