On Sat, May 17, 2014 at 9:59 PM, Hans W Borchers <[email protected]> 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

For this particular example, I'd suggest you just return i-1 directly
inside the loop:

function testfun1(x::Vector{Float64})
    for i = 1:length(x)
        if x[i] == 0.0
            return i-1
        end
    end
    return length(x)-1 # Or other special case for when 0 isn't found
end

Using an early return like this is really quite powerful, especially when
you have a deeply nested set of loops.  I use it all the time in C++.

> 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.

Yes, if you want i accessible outside a loop, you'll just have to declare
it in the outer scope.  AFAIK you've done the right thing there, though
initializing i to a default would be more concise and wouldn't fail if the
input array is empty (unless that's intentional).

> This works, but I must admit it runs against my gut feeling and
> experience with other scientific programming languages.

It's true that the looser scoping rules of langauges like matlab and python
can be convenient.  On the whole I prefer tighter scoping rules like C++
though: they make code easier to reason about by making the data
flow more local.

~Chris

Reply via email to