Search code examples
schemesicp

SICP The Picture Language Exercise Lambda Argument


(define (segments->painter segment-list)
  (lambda (frame)
    (for-each
      (lambda (segment)
        (draw-line
          ((frame-coord-map frame)
           (start-segment segment))
          ((frame-coord-map frame)
           (end-segment segment))))
      segment-list)))

Some of you have already seen this sicp example before but for the first timers a brief explanation: segments->painter procedure takes arguments from segment list which has values are segments made up from vectors. for-each procedure acts like map but instead returns a list of value, it does operations like printing or in this code it draws lines. frame-coord-map scales frames according to unit square frame. What I don't understand in this code is where does first lambda function takes its argument (frame) from.


Solution

  • Here is a case of currying.

    In your code

    (define (segments->painter segment-list)
      (lambda (frame)
         ...))
    

    when you call segments->painter, scheme will return an object of some type, let us call figure. When you apply a graphical frame on this object, scheme will be able to draw your object.

    (define obj1 (segments->painter seg1))
    

    obj1 is an object of type figure and this object is able to receive frames. It is able to do only one action when it receives a frame, namely to get drawn in that frame: (obj1 frame1), (obj1 frame2), etc are actions you can do on that object.

    Before to apply the graphical data on some object, it does make sense to talk about that object but it does not make sense to talk about a real representation of that object. In your case, the object can do one single action: to get drawn.

    Between calling the contructor for the figure object and drawing the object you can do some (static) preprocessing, such that in the moment when you call the drawing method, you have already precomputed something.

    This is how types are implemented in programming languages. This Peter Henderson's language is a first introduction to types and to combinators. This will be developped further in the 4th chapter, where the interpreter uses some precomputed data to execute (it converts the list input format to internal format).