Plurals
, squares
, and exaggerate wordlist
all have almost identical scripts:
The only difference is the circled part above: the particular function that's applied to item 1 of
the input list. By now you know very well how to generalize a pattern by adding another input to the procedure:
But what do we put in the first input slot of in front of
?
There are two little details you have to learn to finish this definition. The first is that the function
input has to be of Reporter type. You already know how to set an input to be of some other type, such as Number or List. It's the same for Reporter:
The Greek letter λ that appears next to the word function
in the orange oval is a type reminder, just like the︙for lists.
Now you have to know how to apply the function to item 1 of data
. Find the call
block in the Control palette and click on its right arrowhead to give it a second input slot. Then fill it in like this:
That's it! Your first higher order function.
(The version in the Snap! tool library is more complicated because it allows more than one input list. The actual code is kind of messy—not mysterious, just messy. It makes a single list a special case, which it then uses inside itself. There's no need for you to read it, but feel free if you don't mind mess.)
The call
block finds empty input slots in its function input and fills them in with the given input values. In this case, there's only one input value, so it will fill all empty slots. If you'd given more input values, then the number of empty slots would have to equal the number of input values, and they'd be filled in left to right.
Everyone else thinks that higher order functions are way too hard and scary for beginning computer science students. But, once you understand recursion, and understand generalizing a procedure by adding an input, they're really no big deal.
Occasionally a problem comes up that doesn't exactly match the map pattern, but comes close. In that case, you can't use the map
HOF, but your understanding of the recursive map pattern will still help. Here's an example you've seen before:
☞ Fill in the blanks: This script is just like the map pattern except for ______ (base case) and _____ (in the recursive case).
☞ Define this block: