Archive for December, 2009

Exercise 1.4

Sunday, December 20th, 2009

Define the behavior of:

1
2
(define (a-plus-abs-b a b)
    ((if (> b 0) + -) a b))

When a-plus-abs-b is invoked, all the subexpressions are evaluated. Thus, the if special form is evaluated to + when b > 0, otherwise evaluated to -, and applied to the values of a and b.

The equivalent case analysis is:

a-plus-abs-b = \begin{cases}a + b & \mbox{if }b > 0 \\a – b & \mbox{if }b <= 0 \end{cases}

Which simplified is:

a-plus-abs-b = a + |b|

Exercise 1.3

Sunday, December 20th, 2009

Given three numbers, the procedure should return the sum of the square of the two larger numbers:

1
2
3
4
5
6
7
8
9
10
11
(define (>= x y) (not (< x y)))

(define (max x y) (if (>= x y) x y))
                       
(define (square x) (* x x))

(define (squares-sum x y) (+ (square x) (square y)))

(define (sum-larger x y z) (cond ((>= x (max y z)) (squares-sum x (max y z)))
                                 ((>= y (max x z)) (squares-sum y (max x z)))
                                 ((>= z (max x y)) (squares-sum z (max x y)))))
1
(sum-larger 5 6 9)

Value: 117

1
(sum-larger -2 -4 -5)

Value: 20

Exercise 1.2

Sunday, December 20th, 2009

This expression

\dfrac{5 + 4 +(2 - (3 - (6 + \dfrac{4}{5})))}{3(6 - 2)(2 - 7)}

becomes

1
2
(/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5)))))
    (* 3 (- 6 2) (- 2 7)))
Value: -0.246666666666667

I’m yet to learn how to pretty-print code in Scheme.

Exercise 1.1

Sunday, December 20th, 2009

Evaluation of a numeral:

1
10

Value: 10

Prefix notation allows to pass a slew of arguments:

1
(+ 5 3 4)

Value: 12

A simple combination applying an operator to two operands:

1
(- 9 1)

Value: 8

1
(/ 6 2)

Value: 3

Nested combinations are also allowed by the prefix notation:

1
(+ (* 2 4) (- 4 6))

Value: 6

define is a special form that does not follow the read-eval-print loop (REPL):

1
(define a 3)

Value: a

1
(define b (+ a 1))

Value: b

1
(+ a b (* a b))

Value: 19

= is a primitive predicate. A predicate evaluates to either to the constant #f or the constant #t:

1
(= a b)

Value: #f

if is a special form also:

1
2
3
(if (and (> b a) (< b (* a b)))
    b
    a)

Value: 4

cond is a conditional expression used in case analysis:

1
2
3
(cond ((= a 4) 6)
          ((= b 4) (+ 6 7 a))
          (else 25))

Value: 16
--

1
(+ 2 (if (> b a) b a))

Value: 6
--

1
2
3
4
(* (cond ((> a b) a)
              ((< a b) b)
              (else -1))
    (+ a 1))

Value: 16

Test

Saturday, December 19th, 2009

Reading now:

SICP

SICP


This is an example of a code snippet in Scheme:

1
2
3
(define pi 3.141516)
(define radius 10)
(* pi (* radius radius))

This is an example of awesome \LaTeX code:

\overbrace{ 1+2+\cdots+100 }^{5050}

Yeah!