Comprehensions in Julia
Build an array from an expression, a range, and an optional filter.
mags = [2.1, 5.8, 3.4, 7.2, 4.9]
# A comprehension maps an expression over a range or collection.
fluxes = [10.0^(-0.4m) for m in mags]
println(round.(fluxes, digits = 3))
# A trailing if filters while it builds.
naked_eye = [m for m in mags if m <= 6.0]
println("$(length(naked_eye)) naked-eye targets")
# Two generators nest into pairs.
grid = [(row, col) for row in 1:2, col in 1:3]
println(grid)
How it works
[10.0^(-0.4m) for m in mags]maps — note the implicit multiply.- A trailing
iffilters while building. - Two generators separated by a comma build a 2-D array.
Keywords and builtins used here
forifin
The run, in numbers
- Lines
- 13
- Characters to type
- 402
- Tokens
- 94
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 87 seconds.
Step 3 of 3 in Control flow, step 6 of 27 in Language basics.