University of California, Berkeley
EECS Department - Computer Science Division

CS3 Lecture 5 : Variables


Overview of today's lecture


Answers to questions that have come up

Review


Variables (chapter 7)

Introduction

How Little People Do Variables

: (define (square x) (* x x))
square

: (sqrt (+ (square 3) (square 4)))
5

Global and Local Variables

: (define four 4)
four

: four 
==> 4 

: x  ;; from the square program earlier 
==> *** ERROR -- Unbound variable: x
: (define (five) 5)
five 

: five 
==> #[procedure five] 

: (five) 
==> 5
==> (+ four (five)) 
9
: (define (my-age-next-presidential-election age) (+ age four)) 
my-age-next-presidential-election 

: (my-age-next-presidential-election 19) 
==> 23
: (define (my-age-next-senate-election age) (+ age six)) 
my-age-next-senate-election 

: (my-age-next-senate-election 19)
==> *** ERROR IN my-age-next-senate-election -- Unbound variable: six 

: (define six 6) 
six
 
: (my-age-next-senate-election 19) 
==> 25

Let : A way to do local variables

(let ( (variable1 value1)
       (variable2 value2)
       ...
       (variableN valueN) )
   body )
: (let ((a (+ 1 1))
        (b 3))
     (+ a b))
==> 5
: (let ((a (+ 1 1))
        (b a))
     (+ a b))
==> *** ERROR -- Unbound variable: a


Summary

Next Time

Puzzle : Light bulbs in the attic, switches in the basement

Game : Nim [BerlekampConwayGuy82]

References


WWW Maven: Dan Garcia (ddgarcia@cs.berkeley.edu) Send me feedback

Dan Garcia Berkeley Computer Science