Hi,

I would do a while as the loop is a conditional loop :

function test(x::Vector{Float64})
    i = 1
    while i <= length(x) && x[i] != 0.0
        i += 1
    end
    return i - 1
end

or I would use a return inside the for loop even though I prefer to avoid a 
return in the middle of a function. Using a loop variable outside the loop 
looks ugly to me. But it's a matter of taste.

On Saturday, May 17, 2014 1:59:02 PM UTC+2, Hans W Borchers wrote:
>
> Yesterday I implemented a function calculating arc length of curves (to 
> the last digit) when I came across the following stumbling blocks. Image 
> the following function where I leave a for-loop with a 'break' statement:
>
>     function testfun1(x::Vector{Float64})
>         for i = 1:length(x)
>             if x[i] == 0.0
>                 break
>             end
>         end
>         return i-1
>     end
>
>     julia> testfun([1.0, 2.0, 3.0, 0.0, 1.0])
>     ERROR: i not defined
>      in testfun at none:7
>
> I understand that the scope of the loop variable is restricted to the loop 
> itself. What is the best way to "export"  i  to the outside? For the 
> moment I settled with defining i before the loop.
>
>

Reply via email to