Note: italicized outcomes are the ones we didn’t get to during Lecture 2.
lambda
let
and let*
.if
and
cond
define base 4) ; syntax: (define <symbol> <value>)
(define height 2)
(
base
; area of a triangle with base 4 and height 2 = 1/2 * base * height
/ (* base height) 2) (
lambda
special
form:lambda (x) (+ x 2)) ; evaluates to a function (or procedure)
(lambda (x) (+ x 2)) 4) ; applies the function to the argument 4
((
define addxy (lambda (x y) (+ x y))) ; store a function in a global variable
(4 8) ; apply the function to 2 arguments (addxy
Do exercise Part A
Scope in Racket is lexical - variables are visible
only within a certain segment of the program text. define
creates global variables whose scope is the entire program.
Function parameters (x
and y
, in the
addxy
example above) are local variables.
They’re only visible inside the procedure body, and they
shadow any global variable with the same name.
define x 1)
(4 5) ; should be 9, because the x inside addxy gets bound to 4, shadowing global x (addxy
If you want to create local variables that are not function
parameters, you can do that with let
:
let ((var1 val1)
(
(var2 val2)
(var3 val3))
(expression-using-variables))
; var1 and friends are not visible here
define a 4)
(
let ((a 1) ; shadows the global a
(2))
(b + a b)) (
The local variables initializations happen (conceptually, though not actually) in parallel. This means a later one can’t reference an earlier one:
let ((a 1)
(+ a 1))) ; error: a is undefined!
(b (+ a b)) (
We could nest let
s to make this work:
let ((a 1))
(let ((b (+ a 1)))
(+ a b))) ; this works (
There’s a shorthand syntax for this - let*
:
let* ((a 1)
(+ a 1)))
(b (+ a b)) (
(if test val-if-true val-if-false)
define absolute-value ; abs is a builtin
(lambda (x)
(if (< x 0)
(- x)
( x)))
Equivalent to your familiar if/elseif/elseif/else chain:
cond ((test1 val-if-test1)
(
(test2 val-if-test2)else val-otherwise))) (
define sign
(lambda (x)
(cond ((< x 0) -1)
(= x 0) 0)
((else 1)))) (
Do Exercises Part B - I recommend working through these at home tonight if we don’t have time to finish them in class.
Definition: Suppose \(A\) and \(B\) are sets. If every element of \(A\) is also an element of \(B\), then \(A\) is a subset of \(B\); this is denoted \(A \subseteq B\).
For example, let:
Then the following are true:
Aside: If \(A \subseteq B\) and \(A \ne B\), then \(A\) is a proper subset of \(B\), denoted \(A \subset B\).
Definition: The power set of a set \(A\) is the set of all subsets of \(A\). It is denoted \(\mathcal{P}(A)\), or sometimes \(2^A\). In other words, \(\mathcal{P}(A) = \{S : S \subseteq A\}\).
Do Exercises Part C