icon

2018-11-20

sicp

It doesn't matter much what the programs are about or what applications they serve. What does matter is how well they perform and how smoothly they fit with other programs in the creation of still greater programs.

The computers are never large enough or fast enough. Each breakthrough in hardware technology leads to more massive programming enterprises, ...

scheme 101

(define (p) (p))
(define (test x y)
  (if (= x 0) 0 y))

(test 0 (p))
  • applicative-order: first evaluates the operator and operands and then applies the resulting procedure to the resulting arguments.
  • normal-order: fully expand and then reduce

For exercies 1.5, see this

(define (square x) (* x x))

; (cond (<p1> <e1>)
;       (<p2> <e2>)
;       ...
;       (<pn> <en>)
;       [(else <e>)])
(define (abs1 x)
  (cond ((> x 0) x)
        ((= x 0) 0)
        ((< x 0) (- x))))

; (cond (<p> <e>)
;       (else <e>))
(define (abs2 x)
  (cond ((< x 0) (- x))
        (else x)))


; (if <predicate> <consequent> <alternative>)
(define (abs3 x)
  (if (< x 0)
      (- x)
      x))

; (and <e1> ... <en>)
; (or <e1> ... <en>)
; (not <e>)

(define (>= x y) (or (> x y) (= x y)))
; (define (>= x y) (not (< x y)))
(print (>= 2 1))
(print (>= 1 2))

process model

Don't be confused by recursive procedure(syntactic) and recursive process(how it evolves)

; linear recursive process
(define (fact x)
  (if (= x 1)
    1
    (* x (fact (- x 1)))))

; linear iterative process, where states is completely captured by the parameters
; tail-recursive, no need of loop
(define (fact2 x)
  (define (fact-iter product cnt maxcnt)
    (if (> cnt maxcnt)
      product
      (fact-iter (* product cnt)
                  (+ 1 cnt)
                  maxcnt)))
  (fact-iter 1 1 x))


(display (fact 66))
(display "\n")
(display (fact2 66))
(display "\n")

let expresion

(let ((<var1> <exp1>)
      (<var2> <exp2>)
     ...
     (<varn> <expn>))
    <body>)

; same as
((lambda (<var1> ... <varn>)
    <body>)
  <exp1>
  ...
  <expn>)
comments powered by Disqus

search See also