Skip to content

Instantly share code, notes, and snippets.

@Patrikios
Last active September 19, 2022 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Patrikios/a8b3d4cf45da88178b527c70de212535 to your computer and use it in GitHub Desktop.
Save Patrikios/a8b3d4cf45da88178b527c70de212535 to your computer and use it in GitHub Desktop.
GEnerator Expressions in julialang
# Generator Expressions
# - comprehensions can also be written without the enclosing square brackets, producing an object known as a generator
# - can be iterated to produce values on demand, instead of allocating an array and storing them in advance
# - Generators are implemented via inner functions.
# - simple example
(1/n^2 for n=1:1000)
# - collect
collect(1/n^2 for n=1:1000)
# - the following expression sums a series without allocating memory
map(tuple, (1/(i+j) for i=1:2, j=1:2), [1 3; 2 4])
# is the same logic as
map(tuple, [0.5 0.33333; 0.33333 0.25], [1 3; 2 4])
# ranges in generators and comprehensions can depend on previous ranges by writing multiple for keywords
[(i,j) for i=1:3 for j=1:i]
# Generated values can be filtered using the if keyword
[(i,j) for i=1:3 for j=1:i if i+j == 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment