sicp-2.1.1-2.1.3
Posted on 2015-02-16 19:31:58 +0900 in SICP
2.1
(define (number x) (car x))
(define (denom x) (cdr x))
(define (make-rat n d)
(let ((g (gcd n d)))
(if (> d 0)
(cons (/ n g) (/ d g))
(cons (/ (- n) g) (/ (- d) g)))))
(define (print-rat x)
(newline)
(display (number x))
(display "/")
(display (denom x)))
2.2
(define (print-point p)
(newline)
(display "(")
(display (x-point p))
(display ",")
(display (y-point p))
(display ")"))
(define (make-segment a b) (cons a b))
(define (start-segment s) (car s))
(define (end-segment s) (cdr s))
(define (make-point x y) (cons x y))
(define (x-point p) (car p))
(define (y-point p) (cdr p))
(define (midpoint-segment s)
(make-point
(/
(+
(x-point (start-segment s))
(x-point (end-segment s)))
2)
(/
(+
(y-point (start-segment s))
(y-point (end-segment s)))
2)))
2.3
;define rectangle using two points
(define (make-rec a b) (cons a b))
(define (rect-width r)
(abs (-
(x-point (car r))
(x-point (cdr r)))))
(define (rect-height r)
(abs (-
(y-point (car r))
(y-point (cdr r)))))
(define (rect-perimeter r)
(* 2 (+ (rect-width r) (rect-height r))))
(define (rect-area r)
(* (rect-width r) (rect-height r)))
;define rectangle using base point, width and height
(define (make-rect p w h) (cons p (cons w h)))
(define (rect-width r)
(car (cdr r)))
(define (rect-height r)
(cdr (cdr r)))
2.4
Lambda
is the ultimate way to represent everyting.
(define (proc-cons x y)
(lambda (m) (m x y)))
(define (proc-car z)
(z (lambda (p q) p)))
(define (proc-cdr z)
(z (lambda (p q) q)))
2.5
(define (math-cons a b)
(* (expt 2 a)
(expt 3 b)))
(define (math-car s)
(get-degree s 2))
(define (math-cdr s)
(get-degree s 3))
2.6
Quote from wiki:
Church numerals are the representations of
natural numbers
under Church encoding. The higher-order function that represents natural numbern
is a function that maps any functionf
to itsn-fold
composition.
To make it more interesting, church-multi
method is added in as well.
Lambda calculas
is really powerful.
(define zero (lambda (f) (lambda (x) x)))
(define (add-1 n)
(lambda (f) (lambda (x) (f ((n f) x)))))
(define one
(lambda (f) (lambda (x) (f x))))
(define two
(lambda (f) (lambda (x) (f (f x)))))
(define (church-add a b)
(lambda (f) (lambda (x) ((a f) ((b f) x)))))
(define (church-multi a b)
(lambda (f) (lambda (x) ((a (b f)) x))))
Hide Comments
comments powered by Disqus