typestar

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

  1. a -> a > 30 is an anonymous predicate for filter.
  2. map(alts) do alt ... end passes the block as the function.
  3. foreach(println, plans) applies without collecting.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Functions, step 9 of 27 in Language basics.

← Previous Next →