Last active
September 19, 2022 15:24
-
-
Save Patrikios/a8b3d4cf45da88178b527c70de212535 to your computer and use it in GitHub Desktop.
GEnerator Expressions in julialang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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