Changes between Version 3 and Version 4 of Tutorial0


Ignore:
Timestamp:
Nov 17, 2012, 9:10:43 AM (9 years ago)
Author:
schiptsov
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • Tutorial0

    v3 v4  
    7575Remember, that this is just a syntactic sugar. The logic is described above.
    7676
     77'''helper procedures'''
     78
     79A helper procedure is used to isolate some piece of code for clarity and re-use
     80{{{
     81(define (sort l)
     82   (if (null? l)
     83       '()
     84       (insert (car l)        ; invoking a helper procedure
     85          (sort (cdr l)))))
     86
     87(define (insert n l)
     88   (cond ((null? l) (cons n '()))
     89         ((< n (car l)) (cons n l))
     90         (else (cons (car l) (insert n (cdr l))))))
     91}}}
     92This sorting procedure calls a helper procedure for each element of given list, to place it properly in the already sorted result list. It works the same way people sort a hand of cards, by taking one card and inserting it into appropriate position.
     93
     94'''nested procedures'''
     95
     96We could define a procedure inside another procedure:
     97{{{
     98(define (squares l)
     99   (define square (lambda (x)     ; defining a procedure inside another procedure
     100                     (* x x)))
     101   (if (null? l)
     102      ()
     103      (cons (square (car l))
     104         (squares (cdr l)))))
     105}}}
     106The underlying idea is very simple - create a new procedure and a binding for it inside another procedure. That means it will be visible and callable only within that procedure, like any other local bindings.
     107
     108We do this to make a procedure and associated symbol private to this frame of environment. Each procedure has its own frame of environment, linked to the parent environment, in which the function was created.
     109
     110So, the global environment is just a list of frames and pre-defined bindings. Each frame is a list of bindings. Everything in Lisp logically is a list of pair. This one of the sources of its magic.
     111
    77112'''let'''
    78113