10-07-2013

posted Oct 7, 2013, 6:20 AM by Samuel Konstantinovich   [ updated Oct 7, 2013, 7:23 AM ]
Goal: Lists (aka the bizarre land of car and cdr)

A few things to remember:
Strings are blocks of text surrounded by double quotes: 
"This is a string"  
"Hello"
"My name is Tony Montana, \nyou killed my father prepare to die." 

You can only put spaces into strings, not into the single quote notation.

This is different from starting with a single quote because the single quotes is only for one word:
Four separate words: 'Fish 'Sticks 'Are 'Yummy

What the apostrophe '  actually does: The following word or expression is not to be evaluated:

(define x 3)
x -> 3
'x -> x

(+ 2 3) -> 5
'(+ 2 3) -> (+ 2 3)

We sometimes use this to show words, other times to make a list of multiple elements such as:
'( 1 2 3 9 4)

LISTS:

These are lists, if you type them into the shell they print back.
'( 1 2 3 9 4)
'( a b f z 2)
'( 9.0 2.3 1 4 table) 

You can define lists just like any variable:
(define name List)
or 
(define L '( 5 9 2 3) )   
(define L2 '( the one and only fish fry champion Jed ) )

Lets consider L and L2 as defined above.
 
length is a function that works on lists: (length List)
(length L) -> 4
(length L2) -> 8

car and cdr are functions that work on lists also:

(car List) : the 1st element of the list e.g.
(car L) -> 5
(car L2) -> the

(cdr List) : the List with the 1st element removed e.g.
(cdr L) -> (9 2 3)
(cdr L2) -> (one and only fish fry champion Jed)

Since cdr returns a list, you can use car or cdr on it:
(car (cdr L) ) -> 9  
(car (cdr L2) ) -> one

(cdr (cdr L) ) -> (2 3)
(cdr (cdr L2) ) -> (and only fish fry champion Jed)

You can chain together any number or car and cdr to extract any element from the list:
(car  (cdr (cdr (cdr List ) ) ) )
This would remove the first three elements, gives the 1st one from that list (the 4th element of the original list)

(car  (cdr (cdr (cdr L ) ) ) ) -> 3







Comments