Ok, I now see that `all` isn't short-circuiting, which is kind of
surprising/annoying. Anyone know why that is?

You can easily define your own short-circuiting `all` to do this:

all′(f, xs) =
  isempty(xs) ? true :
  f(xs[1]) && all′(f, xs[2:end])

The other thing you could try is to check out Lazy.jl. If you call, for
example,

@time all(map(f,list(1,2,3,5)))

The `list` construct actually takes care of short-circuiting for you, so
what looks like a very expensive `map` operation is actually very cheap.

On 30 January 2015 at 08:05, Mike Innes <[email protected]> wrote:

> How about `all(f, values)`?
>
> On 30 January 2015 at 06:51, Wai Yip Tung <[email protected]> wrote:
>
>> I want to apply function f() over a range of value. f() returns true for
>> success and false for failure. Since f() is expensive, I want short circuit
>> computation, i.e. it stops after the first failure.
>>
>> In python, I can do this in an elegant way with the all() function and
>> generator expression.
>>
>> if all(f(x) for x in values)
>>   # success
>> else
>>   # failure
>>
>> From what I understand, there is no generator expression in Julia. List
>> comprehension will evaluate the full list. Even if I try to use for loop, I
>> can't use the control variable to check if the loop has run to finish or
>> not.
>>
>> i = 0
>> for i in 1:length(values)
>>     if !f(values[i])
>>       break
>>    end
>> end
>> # The status is ambiguous if i==length(values)
>>
>> My last resort is to add flags to indicate if is success or not. Is there
>> some more elegant way to do this?
>>
>>
>

Reply via email to