11-04-2013 LAB42

posted Nov 4, 2013, 5:29 AM by Samuel Konstantinovich   [ updated Nov 4, 2013, 8:30 AM ]
Goal: Creating lists with cons.

Two new commands:

The LIST command:
(list x)  will take the value in x and make it into a list

(list 5) -> (5)
(list "A") -> ("A")

At first this doesn't seem useful because it is the same as saying '(5) or '("A")

However if there is a variable n that has a number 3 in it:
'(n) -> (n)
(list n) -> (3)

The list command is the only way to put a variable or expression into a list!
(list (+ 2 3)) -> (5)
'( (+ 2 3)) ->  ( (+ 2 3)) 

Cons inserts an element into the beginning of a list.

(cons x L)  takes x, and placees it INSIDE The list in the beginning.
(cons 1 '(9 3) ) -> (1 9 3)
(cons 2 '() ) -> (2)
(cons '(a b) '(c d) ) -> ( (a b) c d)

This is how we add to a list, or create one from scratch.


(define buildList (lambda (n) 
                    (if (= n 0)
                        '()
                        (cons n (buildList (- n 1))))))
(define buildlist2 (lambda (n stop) 
                    (if (<= n stop)
                        '()
                        (cons n (buildlist2 (- n 1) stop)))))
Trace these functions:
(buildlist 3)
(buildlist2 21 19)


LAB 42: (COMPLETE ALL 4 problems at home by Wednesday in class.)
*MAKE SURE ALL THE FUNCTIONS ARE NAMED CORRECTLY!
*MAKE SURE YOU HAVE A FILE IN THE LAB THAT YOU CAN RUN ON WEDNESDAY!
1. Write a function (listsquares n) that returns the list of perfect squares from 1 to n^2 in decreasing order.
(listsquares 3) -> (9 4 1)
(listsquares 5) -> (25 16 9 4 1)

2a. Write a function (listsquares2 a b) that returns the list of perfect squares from a^2 to b^2 in increasing order. Assume a<b for now.
(listsquares2 3 5) -> (9 16 25)
2b. Improve the function so that if the numbers are not in the right order you must handle them properly: 
(listsquares2 6 4) -> (16 25 36)
(listsquares2 4 6) -> (16 25 36)


3. Write a function (listhail n) that returns a list of the hail sequence started with n.
(listhail 4) -> (4 2 1)
(listhail 5) -> (5 16 8 4 2 1)


4. Write a function (filterEven L) that takes a list of integers, and returns the same list with all of the even values removed:
(filterEven '(1 2 3 4 5)
 ) -> (1 3 5)
(filterEven '(8 6 7 5 3 0 9)
 ) -> (7 5 3 9)

5. (bonus point for completion) Write a function (fixList L) that will return the same list but changes all odd numbers into even numbers by adding 1 to them:
(fixList '(1 2 3 4 5)) -> (2 2 4 4 6)
(fixlist '(8 6 7 5 3 0 9)) -> (8 6 8 6 4 0 10)

6. (bonus point for completion)  Write a function  (weaveTogether L1 L2) that takes 2 lists and merges them together by alternating values: (L1First, L2First, L1Second, L2Second...  ) When one list runs out, the rest of the values of the non-empty list are used.

(weaveTogether '( a b c ) '(1 2 3 4)) -> ( a 1 b 2 c 3 4)
(weaveTogether '( a b c d e) '(1 2 )) -> ( a 1 b 2 c d e)
(weaveTogether '( ) '(1 a 2 b )) -> ( 1 a 2 b)
Comments