CS152
Chris Pollett
Apr. 6, 2009
How can you do looping if you have a pure functional programming language?
for(int i=0; i <10; i++) {/*do something */} Seems to require variables; however, we can replace it with recursion: void my_for(int i, int stop, int step) { if ( i < stop) { /* do something */ my_for(i+ step, stop, step) } } my_for(0, 10, 1);
Which of the following statements is true?
<expression> ::= <atom> | <list> <atom> ::= <number> | <string> | <identifier> | <character>| <boolean> <list> ::= '(' <expression-sequence> ')' <expression-sequence> ::= <expression> <expression-sequence> | <expression>
42 - a number "hello" - a string #t - a Boolean true #\a - the character 'a' (2.1 2.2 3.1) - a list of numbers a - an identifier hello - another identifier (+ 2 3) - a list consisting of the identifier "+" and two numbers (* (+ 2 3) (- 4 3) ) - a list consisting of an identifier and two lists
To evaluate expressions we use the rules:
(if (= a 0) (display "zero") (display "not zero")) ; displays echoes to current output ; semicolon is used for comments cond (sorta like switch/case): (cond ((= a 0) (display "zero")) ((> a 0) (display "bigger than zero")) ((= a -1) (display "minus one")) (else (display "less than -1")))
(let ((a 2) (b 3)) (+ a b)) ; evaluates to 5
The define function can be used to add new associations between names and values in Scheme:
(define a 2) (define emptylist '()) (define (sum lo hi) ; could write: sum (lambda (lo hi) ... (if (= lo hi) lo (+ lo (sum (+ lo 1) hi))) )
Once something has been define can see its value are scheme prompt
>(sum 3 5) 12