它是环“假”,所以你不能break
它。看一看下面的降低代码:
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)
输出显示array comprehension
经由Base.Generator
这需要一个迭代作为输入来实现。目前它只支持[if cond(x)::Bool]
“警卫”,所以在这里没有办法使用break
。
针对您的特殊情况下,一个解决方法是使用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)
在后面的问题http://stackoverflow.com/questions/44101965/array-comprehension-with-a-random-output-in-julia(编辑:和更近的答案在这里)有评论说它最好只写出循环。我同意这一点 - 这只是试图回答提出的问题。 –