Created
June 16, 2011 21:08
-
-
Save klandergren/1030282 to your computer and use it in GitHub Desktop.
sunnycloud W2L5 exercises
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ;; 2.17 | |
| ;; Helpful link on equivalence | |
| ;; http://sicp.ai.mit.edu/Fall-2003/manuals/scheme-7.5.5/doc/scheme_4.html | |
| (define (last-pair list) | |
| (if (null? (cdr list)) | |
| (car list) ;; fixed paren error | |
| (last-pair (cdr list)))) | |
| ;; testing | |
| (last-pair (list 1 2 3 4 5 6 4 3 23)) ;; => 23 | |
| (define (length alist) | |
| (define (list-iter alist count) | |
| (if (null? alist) | |
| count | |
| (list-iter (cdr alist) (+ 1 count)))) | |
| (list-iter alist 0)) | |
| (length (list 1 2 3 4)) ;; => 4 | |
| ;; 2.18 fails for me | |
| ;; Think of 2.18 in terms of 2.17: if you can find the last pair of a list | |
| ;; can't you call that recursively to build a new list last-element to first? | |
| (define (last-pair list) | |
| (if (null? (cdr list)) | |
| (car list) ;; fixed paren error | |
| (last-pair (cdr list)))) | |
| ; returns list without last element using same proc structre as last-pair | |
| (define (remove-last-element l) | |
| (if (null? (cdr l)) | |
| () | |
| (append (list (car l)) (remove-last-element (cdr l))))) | |
| (define (reverse l) | |
| (if (null? l) | |
| () | |
| (append (list (last-pair l)) (reverse (remove-last-element l))))) | |
| ;; Testing | |
| (remove-last-element (list 1 2 3 4)) | |
| (last-pair (list 1 3 4 5)) | |
| (reverse (list 1 4 9 16 25)) ;; => (list 25 16 9 4 1) | |
| ;; a different tact: (to me more intuitive) | |
| (define (reverse-iter l) | |
| (define (r-helper tail reversed-list) | |
| (if (null? tail) | |
| reversed-list | |
| (r-helper (cdr tail) | |
| (append (list (car tail)) reversed-list)))) | |
| (r-helper (cdr l) (list (car l)))) | |
| ;; Testing | |
| (reverse-iter (list 1 4 9 16 25)) ;; => (list 25 16 9 4 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment