You could also use a list comprehension without enumerate:

d=[6,5,4,3,2,1,0]
n=4
sum(d[ Bool[i<=n && d[i]!=i && d[d[i]]==i for i in 1:length(d)]   ] )

>> 18

Coming from numpy, I find this syntax intuitive, aside from the requirement 
to explicitly set the comprehension type to Bool.

On Thursday, June 19, 2014 11:57:04 AM UTC-4, Matt Bauman wrote:
>
> There's also an open issue about "splitting" or "splatting" of tuples 
> within function arguments that's very relevant here: Allow tuple 
> destructuring in formal arguments, 
> https://github.com/JuliaLang/julia/issues/6614
>
> It's a common use case that I run into often, especially with enumerate 
> and dictionaries.  So you're not alone.
>
> On Thursday, June 19, 2014 3:57:33 AM UTC-4, gentlebeldin wrote:
>>
>> Ah, I see, multiple dispatch is the real cause. I'll have to live with 
>> the little ideosyncrasy, then.
>> Peter's idea filter(p -> +(p...)%4 != 0, pairs) works fine... in my 
>> simple example. In real life, I wanted to filter an array d of integers, 
>> with a predicate
>> i<=n && d[i]!=i && d[d[i]]==i, so filter((i,v)->i<=n && v!=i && 
>> d[v]==i,enumerate(d)) looked like a reasonable idea, it just doesn't work. 
>> We can make it work, though that looks a bit strange, too:
>> filter([e for e in enumerate(d)]) do x
>>        i,v=x
>>        i<=n && v!=i && d[v]==i       
>>        end
>> Here, it looks as if the function filter took only one argument. It 
>> works, however. In my code, I had to sum up the values of i after 
>> filtering, so I chose the obscure formulation
>> sum(map(first,filter(x->x[1]!=x[2] && x[2]<=n && 
>> d[x[2]]==x[1],enumerate(d))))
>>
>>>
>>>>

Reply via email to