Skip to content

Instantly share code, notes, and snippets.

@evertrol
Last active February 6, 2020 16:25
Show Gist options
  • Save evertrol/8119458ad7f67c01d37417702a112da1 to your computer and use it in GitHub Desktop.
Save evertrol/8119458ad7f67c01d37417702a112da1 to your computer and use it in GitHub Desktop.
Julia array / list comprehension and generator expression examples
julia> VERSION
v"1.3.0"
julia> # Julia documention on array) comprehensions and generator expressions:
julia> # https://docs.julialang.org/en/v1/manual/arrays/#Comprehensions-1
julia> # https://docs.julialang.org/en/v1/manual/arrays/#Generator-Expressions-1
julia> # The code below uses generator expressions
julia> # Double list comprehension for the first fifty-one terms of the power series of the exponential function
julia> sum(prod(1/i for i in 1:n) for n in 1:50) + 1
2.7182818284590455
julia> # As a function (function assignment form)
julia> f(x) = sum(prod(x/i for i in 1:n) for n in 1:50) + 1
f (generic function with 1 method)
julia> f(1)
2.7182818284590455
julia> # Accuracy of the approximation
julia> f(15) - exp(15)
-8.638016879558563e-7
julia> # Nested list comprehension with conditional
julia> prod(i^2 for n in 1:10 for i in 1:n if i % 3 == 1)
154747698518425600
julia> # Using '=' instead of 'in'; this is identical
julia> prod(i^2 for n = 1:10 for i = 1:n if i % 3 == 1)
154747698518425600
julia> # Two-dimensional list comprehension
julia> [x * y for x in 2:2:10, y in 10:10:50]
5×5 Array{Int64,2}:
20 40 60 80 100
40 80 120 160 200
60 120 180 240 300
80 160 240 320 400
100 200 300 400 500
julia> # With a conditional, thus reduces to a one-dimensional array
julia> [x * y for x in 2:2:10, y in 10:10:50 if 3x > y]
6-element Array{Int64,1}:
40
60
80
100
160
200
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment