You could also split that into multiple lines if readability is your goal:

~~~
sum(map(first,filter(x->x[1]!=x[2] && x[2]<=n &&
d[x[2]]==x[1],enumerate(d))))
~~~

becomes:

~~~
filtered = filter(enumerate(d)) do x
  x[1]!=x[2] && x[2]<=n && d[x[2]]==x[1] #expand to readability as desired
end
final = sum(map(first,filtered))
~~~

I'm not sure whether you "looks as if filter took only one argument"
comment was a request for explanation, but just in case: `do` syntax makes
the expression that follows it an anonymous function and passes it in as
the first argument to the preceding function call. You could use a
begin-end block in an in-line anonymous function to get the same effect
without do syntax.

Splitting this operation out over more lines won't affect efficiency; the
code is already allocating the temporary arrays (output of filter, output
of map), so giving them names won't cause the behavior to change. Splitting
this out over more lines with more variable names might make it easier to
read.

-- Leah


On Thu, Jun 19, 2014 at 2:57 AM, gentlebeldin <[email protected]>
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