Skip to content

Instantly share code, notes, and snippets.

@gar
Created October 10, 2010 21:23
Show Gist options
  • Save gar/619582 to your computer and use it in GitHub Desktop.
Save gar/619582 to your computer and use it in GitHub Desktop.
; SICP Exercise 1.1
10 => 10
(+ 5 3 4) => 12
(- 9 1) => 8
(/ 6 2) => 3
(+ (* 2 4) (- 4 6)) => 6
(define a 3)
(define b (+ a 1))
(+ a b (* a b)) => 19
(= a b) => #f
(if (and (> b a) (< b (* a b)))
b
a) => #t
(cond ((= a 4) 6)
((= b 4) (+ 6 7 a))
(else 25)) => 16
(+ 2 (if (> b a) b a)) => 6
(* (cond ((> a b) a)
((< a b) b)
(else -1))
(+ a 1)) => 16
; SICP Exercise 1.2
#lang racket
(/ (+ 5 4
(- 2
(- 3
(+ 6
(/ 1 3)))))
(* 2
(- 6 2)
(- 2 7)))
; SICP Exercise 1.3
#lang racket
(define (square a)
(* a a))
(define (sum-squares a b)
(+ (square a) (square b)))
(define (f a b c)
(cond ((and (>= a c) (>= b c)) (sum-squares a b))
((and (>= a b) (>= c b)) (sum-squares a c))
((and (>= b a) (>= c a)) (sum-squares b c))))
(f 1 2 3)
(f 9 5 7)
(f 9 9 1)
(f 5 5 5)
; SICP Exercise 1.4
(define (a-plus-abs-b a b)
((if (> b 0) + -) a b))
In the above procedure, the operator on the second line varies depending on the sign of 'b', either subtracting or add the numbers together. In effect, it is add the absolute value of 'b' to 'a'.
; SICP Exercise 1.5
(define (p) (p))
(define (test x y) (if (= x 0)
0
y))
(test 0 (p))
If the interpretor is using normal-order evaluation, it will try to expand all the operands before evaluating the procedures. In the case of '(test 0 (p))', it would try to evaluate '(p)' and end up in an infinite loop. If applicative-order evaluation is being used, the 'test' procedure would just evaluate to '0' without the need to expand '(p)'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment