diff --git a/ex-2.17.scm b/ex-2.17.scm new file mode 100644 index 0000000..635a86c --- /dev/null +++ b/ex-2.17.scm @@ -0,0 +1,7 @@ +#lang sicp + +(define (last-pair list) + (cond ((null? list) (error "Can't get last element of empty list")) + ((null? (cdr list)) list) + (else (last-pair (cdr list))))) + diff --git a/ex-2.18.scm b/ex-2.18.scm new file mode 100644 index 0000000..234285a --- /dev/null +++ b/ex-2.18.scm @@ -0,0 +1,9 @@ +#lang sicp + +(define (reverse lst) + (define (rev-aux lst acc) + (if (null? lst) + acc + (rev-aux (cdr lst) (cons (car lst) + acc)))) + (rev-aux lst '())) diff --git a/ex-2.19.scm b/ex-2.19.scm new file mode 100644 index 0000000..f45202b --- /dev/null +++ b/ex-2.19.scm @@ -0,0 +1,14 @@ +#lang sicp + +(define (first-denomination coin-values) + (car coin-values)) +(define (except-first-denomination coin-values) + (cdr coin-values)) +(define (no-more? coin-values) + (null? coin-values)) + +; The answer will not be affected by the order of the list. We +; are still dividing cases into "doesn't use the first coin" +; and "uses at least one instance of first coin". However I +; suspect it will impact the performace, although I haven't +; formally proven it. diff --git a/ex-2.20.scm b/ex-2.20.scm new file mode 100644 index 0000000..07b5132 --- /dev/null +++ b/ex-2.20.scm @@ -0,0 +1,10 @@ +#lang sicp + +(define (same-parity fst . lst) + (define (same-parity-aux parity lst) + (cond ((null? lst) '()) + ((equal? parity (even? (car lst))) + (cons (car lst) (same-parity-aux parity (cdr lst)))) + (else (same-parity-aux parity (cdr lst))))) + (same-parity-aux (even? fst) + (cons fst lst))) diff --git a/ex-2.21.scm b/ex-2.21.scm new file mode 100644 index 0000000..cd1f2a9 --- /dev/null +++ b/ex-2.21.scm @@ -0,0 +1,11 @@ +#lang sicp + +(define (square x) (* x x)) + +(define (square-list items) + (if (null? items) + nil + (cons (square (car items)) (square-list (cdr items))))) + +(define (square-list2 items) + (map square items)) diff --git a/ex-2.22.txt b/ex-2.22.txt new file mode 100644 index 0000000..7558572 --- /dev/null +++ b/ex-2.22.txt @@ -0,0 +1,18 @@ +When we are running the iter line: +(iter (cdr things) + (cons (square (car things)) + answer)))) +We are essentially pushing on the "answer" accumulator list +like a stack, so when we start with items = (1 2 3), answer = +(). +When we run the loop once we get: +things = (2 3), answer = (1) +things = (3), answer = (4 1) +things = (), answer = (9 4 1). + +When Louis changes the order in the cons, he just produces the +following: +things = (1 2 3), answer = () +things = (2 3), answer = (() . 1) +things = (3), answer = ((() . 1) . 4) +things = (), answer = (((() . 1) . 4) . 9) diff --git a/ex-2.23.scm b/ex-2.23.scm new file mode 100644 index 0000000..857dea2 --- /dev/null +++ b/ex-2.23.scm @@ -0,0 +1,7 @@ +#lang sicp + +(define (my-for-each func list) + (if (null? list) + #t + (begin (func (car list)) + (my-for-each func (cdr list)))))