Section Notes 4
CS51—Spring 2009
Week of February 23, 2009
Outline
1. Higher order functions
(a) lambda!
(b) Passing to functions
(c) Returning from functions
(d) Understanding evaluation for lambda
2. Games!
(a) Game trees
(b) Strategies
(c) Game values
3. Graphs
(a) Probabilitic transitions
(b) Random walks
1
Goals for today:
At the end of today’s section, you should be able to do the following:
1. Write inline lambda functions for use in ﬁlter and map and fold.
2. Manually evaluate a game tree and ﬁnd the optimal strategy.
3. Manually simulate a random walk on a graph
4. Write a function that returns a strategy for a number picking game.
This week’s section will focus on higher order functions and games. As we started to see in class last
week, and as we’ll keep seeing for the rest of the semester, higher order functions are incredibly useful tool
that help make our code more concise and more elegant. Playing games includes very natural applications of
higher order functions, because a strategy in a game is simply a function that determines what to do given
some game state.
1
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document2
Higher order functions
Deﬁning a lambda:
(lambda (x) (stringappend x "  ARRR!"))
What does a lambda expression evaluate to?
Passing it to a function:
(map (lambda (x) (stringappend x "  ARRR!")) myspeech)
Q1: How can we write a single call that will append “– ARRR!” to the end of every string in myspeech,
and then concatenate all of them together.
Using a lambda to
partially apply
a predicate:
(filter (lambda (x) (clique? graph x)) possibletriangles)
Q2: Write
dupdup
, which takes a list and duplicates each element:
(dupdup ’(1 2 3))
should evaluate
to
’(1 1 2 2 3 3)
.
Q3: Write
(numoccurs el lst)
using foldr
Q4: Challenge! Write numoccursdeep using foldr. You can have your function return 1 if el = lst.
Making a function that returns a function:
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '09
 GREGMORRISETT
 Carmen, higher order functions, Higherorder function, Detective Fry Tening

Click to edit the document details