Killing the for loop in Julia array parsing
I have the following line of code in Julia:
X=[(i,i^2) for i in 1:100 if i^2%5==0]
Basically, it returns a list of tuples (i,i^2)
from i=1 to 100
if the remainder i^2
and 5
is zero. What I want to do, in the understanding of an array, break out of the for loop if i^2
it becomes greater than 1000
. However, if I implement
X=[(i,i^2) for i in 1:100 if i^2%5==0 else break end]
I get an error: syntax: expected "]"
.
Is there a way to easily break out of a for loop inside an array? I tried looking on the internet but nothing worked.
source to share
This is a "fake" for-loop, so you can't do break
it. Take a look at the below code:
julia> foo() = [(i,i^2) for i in 1:100 if i^2%5==0]
foo (generic function with 1 method)
julia> @code_lowered foo()
LambdaInfo template for foo() at REPL[0]:1
:(begin
nothing
#1 = $(Expr(:new, :(Main.##1#3)))
SSAValue(0) = #1
#2 = $(Expr(:new, :(Main.##2#4)))
SSAValue(1) = #2
SSAValue(2) = (Main.colon)(1,100)
SSAValue(3) = (Base.Filter)(SSAValue(1),SSAValue(2))
SSAValue(4) = (Base.Generator)(SSAValue(0),SSAValue(3))
return (Base.collect)(SSAValue(4))
end)
The output shows what array comprehension
is implemented through Base.Generator
, which takes an iterator as input. It only supports [if cond(x)::Bool]
"guard", so there is no way to use it here break
.
In your specific case, the workaround is to use isqrt
:
julia> X=[(i,i^2) for i in 1:isqrt(1000) if i^2%5==0]
6-element Array{Tuple{Int64,Int64},1}:
(5,25)
(10,100)
(15,225)
(20,400)
(25,625)
(30,900)
source to share
The use of a loop for
is considered idiomatic in Julia and may be more readable in this case. Also, it could be faster.
In particular:
julia> using BenchmarkTools
julia> tmp(i) = (j = i^2; j > 1000 ? false : j%5==0)
julia> X1 = [(i,i^2) for i in 1:100 if tmp(i)];
julia> @btime [(i,i^2) for i in 1:100 if tmp(i)];
471.883 ns (7 allocations: 528 bytes)
julia> X2 = [(i,i^2) for i in 1:isqrt(1000) if i^2%5==0];
julia> @btime [(i,i^2) for i in 1:isqrt(1000) if i^2%5==0];
281.435 ns (7 allocations: 528 bytes)
julia> function goodsquares()
res = Vector{Tuple{Int,Int}}()
for i=1:100
if i^2%5==0 && i^2<=1000
push!(res,(i,i^2))
elseif i^2>1000
break
end
end
return res
end
julia> X3 = goodsquares();
julia> @btime goodsquares();
129.123 ns (3 allocations: 304 bytes)
So, one more improvement - nothing is worth ignoring, and the long function gives enough room to highlight comments.
source to share