CS 330 Lecture 33 – Fold
Agenda
- what ?s
- program this
- bring * into the fold
- fold1
TODO
- Attend the CV Dev group meeting on Wednesday. Brad Candell of Group Health is speaking on regular expressions. Pizza at 5 PM, talk at 6 PM. They ask you to register so they can order enough pizza. See the Piazza post.
- Start the WASD homework. Since it involves JRuby and GUIs, I implore you to get a local JRuby/Java environment working. The grader isn’t finalized yet, but it will test the non-GUI portions of the assignment on a setup like the thingies.
Note
Today we round out our discussion of the fold pattern. We start by implementing join
and illustrating its execution. Then we see just how encompassing fold is in a Program This:
Write function
map
using ourfold'
function. Recall that it accepts a transformation function, applies it to each element in the list, and gives back a new list.If you finish early, consider how we might write
filter
as a fold.
Back to join
, what if we wish to separate the the strings with some text? What do we do to support that?
Let’s also implement maximum
and minimum
.
Code
folds.hs
-- fold' glom identity list
fold' _ identity [] = identity
fold' glom identity (first:rest) = glom first (fold' glom identity rest)
join' :: [String] -> String
join' = fold' (++) ""
map' xform = fold' (\x accum -> xform x : accum) []
filter' pred = fold' (\x accum -> if pred x then x : accum else accum) []
maximum' [] = error "You are maximum error."
maximum' (first:rest) = fold' max first rest