SICP ch2 building abstractions with Data学习笔记


compound structure:

Pair

use con to generate a pair

(define x (cons 1 2))


Representing rational numbers

(define (make-rat n d) (cons n d))
(define (numer x) (car x))
(define (denom x) (cdr x))
(define (print-rat x)
  (newline)
  (display (numer x))
  (display "/")
  (display (denom x)))

(define m (make-rat 2 7))
(print-rat m)

(define (cons1 x y z)
  (define (dispatch m)
    (cond ((= m 0) x)
          ((= m 1) y)
          (else (error "Argument not 0 or 1 " m))))
  dispatch)

the value returned by procedure cons1 is a procedure(dispatch)


(define (scale-list item factor)
  (if (null? item)
      '()
      (cons (* (car item) factor)
            (scale-list (cdr item) factor))))
直接使用nil会出现nil: unbound identifier in module in: nil
DrRacket中未定义nil,若要使用nil

(define nil ‘())


high-order procedure map,higher level of abstraction in dealing with lists

(define (map proc items)
  (if (null? items)
      nil
      (cons (proc(car items))
            (map proc (cdr items)))))
(map (lambda (x) (* x x))
     (list 1 2 3 4))


你可能感兴趣的:(SICP ch2 building abstractions with Data学习笔记)