Anonymous functions and do in Julia
Arrows for throwaways; do blocks for multi-line arguments.
alts = [22.0, 47.5, 63.0, 81.5]
# Arrow syntax makes a throwaway function.
above_horizon = filter(a -> a > 30, alts)
println(above_horizon)
# do blocks hand a multi-line function to the first argument.
plans = map(alts) do alt
band = alt > 60 ? "zenith" : "low"
"slew to $alt ($band)"
end
foreach(println, plans)
How it works
a -> a > 30is an anonymous predicate forfilter.map(alts) do alt ... endpasses the block as the function.foreach(println, plans)applies without collecting.
Keywords and builtins used here
doend
The run, in numbers
- Lines
- 12
- Characters to type
- 314
- Tokens
- 64
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 59 seconds.
Step 3 of 3 in Functions, step 9 of 27 in Language basics.