What is the advantage of "foreach(v) do.." over "for i in v..."?

Leon_Niceday
Wed, 14 May 2025 18:23:09 +0000
New to Julia

This

julia> let t = 0
           for x in v
               t += x
           end
           t
       end

vs

julia> let t = 0
           foreach(v) do x
               t += x
           end
           t
       end

It appears to me that for can do the same, is not more verbose, has simpler semantics. What’s the real use of the foreach do.. idiom then?

EDIT: Sorry, I should have mentioned that before posting, I had read the docs for for, foreach.
In case interation is over several containers:

julia> shorter =1:2; longer= 'a':'c';

julia> foreach(shorter, longer)  do x,y
           println(x," and ", y)
       end
1 and a
2 and b

julia> for (x,y) in zip(shorter,longer)
           println(x, " and ", y)
       end
1 and a
2 and b

julia> for i in 1:length(shorter)
           println(shorter[i], " and ", longer[i])
       end
1 and a
2 and b

13 posts - 9 participants