Big fan of Julia! My other favorite language is Clojure. In both languages, comprehensions are my goto tool for many purposes. In Clojure, comprehensions provide an assignment feature that I find very useful. Here is an example:
(for [x [0 1 2 3 4 5]
:let [y (* x 3)]
:when (even? y)]
y)
You can use a let
block inside a comprehension in Julia:
julia> [let y = x*3; y^3; end for x in 0:5]
6-element Array{Int64,1}:
0
27
216
729
1728
3375
1 Like
Thanks for your prompt feedback. Iām probably missing something, but here is a sample of existing code:
[f(i,j) for i=1:mx for j=i+1:mx if f(i,j) < n && iseven(f(i,j)))])
Assuming f(i,j) is expensive to run, I would like to just call it once. In Clojure, this is accomplished with the :let symbol. I can clearly do it with a for
statement, but I like the elegance of comprehensions.
Thanks.
1 Like
If a value is expensive and is used in both the result and the filter condition, you can first calculate the value, then filter on it (ie two comprehensions, one inside the other).