Skip to content

Instantly share code, notes, and snippets.

@mackhowell
Created February 4, 2015 05:02
Show Gist options
  • Save mackhowell/62fb5fb92b349f982dd7 to your computer and use it in GitHub Desktop.
Save mackhowell/62fb5fb92b349f982dd7 to your computer and use it in GitHub Desktop.
SICP - ex 1.1 - 1.5
#lang racket
; -- 1.1 --
; (define a 3)
; (define b (+ a 1))
; (+ a b (* a b))
; (if (and (> b a) (< b (* a b)))
; b
; a)
; (cond ((= a 4) 6)
; ((= b 4) (+ 6 7 a))
; (else 25))
; (+ 2 (if (> b a) b a ))
; (* (cond ((> a b) a)
; ((< a b) b)
; (else -1))
; (+ a 1))
; -- 1.2 --
; (/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5)))))
; (* 3 (- 6 2) (- 2 7)))
; -- 1.3 --
; define a procedure that takes three numbers as arguments
; and returns the sum of the squares of the two larger numbers.
; (define (sqr x) (* x x))
; (define (sqr-sum x y)
; (+ (sqr x) (sqr y)))
; (define (mini x y)
; (if (< x y) x y))
; (define (maxi x y)
; (if (> x y) x y))
; (define (answer x y z)
; (sqr-sum (maxi x y) (maxi z (mini x y))))
; (answer 1 2 3)
; -- 1.4 --
; first (if) is evaluated -- and inside of (if) you have ( a b ) and ((> b 0) + -) --
; which is creating an absolute value for b. if b is positive then + ... if b is negative then - .
; the + or - then gets applied as the operator to the second expression
; (which is the second operand of the definition expression).
; -- 1.5 --
(define (p) (p))
(define (test x y)
(if (= x 0)
0
y))
; applicative order:
(test 0 (p))
; the first evaluation in the procedure is (test 0 (p)) which (if using applicative order), the operands will have to be eval'd. this results in a recrusive call p = p.
; so the entire procedure will barf.
; normal order:
(test 0 (p))
(define (test 0 (p))
(if (= 0 0)
0
y))
; --> 0
; in this example the (p) variable is never used because the if statement evaluates to 0. the operands (p) snuck through because 0 got used instead in the if statement.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment