Map
Converts one array into another.
- e.g.,
(map (lambda (x) (* x x)) lst)
- Notice: If the transformation has no side effects, this can be easily parallelized. This is one key motivation for pure functional programming.
- Do some of the In-Class problems.
- Do the “bound” in-class problem.
- Show how to use closures to write a general “bound” function
Fold/Reduce
“Reduce” is a common pattern wherein you
- Iterate over a list
- At each iteration, you use the current item to modify a “partial” answer.
(Consider
sum
andmax
as examples.)
- This function goes by many different names across programming languages:
- Javascript: Reduce
- Ruby: Inject
- Kava: Fold
- The “partial” result goes by many names:
- “Partial”
- “Accumulator”
- “Memo”
- To use
fold
in kawa you must import a library:(require 'list-lib)
- API for this library: https://srfi.schemers.org/srfi-1/srfi-1.html
- In Kawa the parameters to fold are in this order:
- lambda
- initial value
- list
- The parameters to the lambda are in this order
- item
- partial
-
These orders change from language to language!
- Sum values in an array
(require 'list-lib)
(display
(fold (lambda (item partial) (+ item partial)) 0 '(1 2 3 4 5 6)))
(newline)
- Have students implement Max.
- Notice the challenge of choosing the first value.
- Show
reduce
(display
(reduce (lambda (item partial) (if (> item partial) item partial)) 99999999 lst)
)
(newline)
-
count_positive
usingfold
-
Implement
map
usingfold
.