aspose file tools*
The moose likes Clojure and the fly likes Amap idx Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Languages » Clojure
Bookmark "Amap idx" Watch "Amap idx" New topic
Author

Amap idx

jay vas
Ranch Hand

Joined: Aug 30, 2005
Posts: 407
Hi guys: what is the purpose of the Idx parameter in the amap function?

It seems unnecessary to me, since the mapping should be able to worn without a temporary variable....

I assume it must enable some sort of mind bending code gynamstics trick?
Sean Corfield
Ranch Hand

Joined: Feb 09, 2011
Posts: 261
    
    5

Unlike regular map which simply creates a new sequence by applying the function to successive elements of its argument, amap is a macro that does the following:

Copy the array and bind it to ret.

Loops over that array and executes the expression (not a function) with idx bound to successive index values.

This allows for imperative loops and therefore high performance.
jay vas
Ranch Hand

Joined: Aug 30, 2005
Posts: 407
If you are simply iterating over each element and always applying an operation, what is the point of binding ? I'm not sure how that would increase performance.

Typically, for loops might be optimized by the fact that, (outside) the for loop, you might cache or skip a calculation.


But I don't see how idx accomplishes that.
Sean Corfield
Ranch Hand

Joined: Feb 09, 2011
Posts: 261
    
    5

Regular map will create a sequence, not another array so you'd have to convert the result back into an array. amap does it all "in place" and it achieves that by allowing you to specify an expression that can contain a loop variable, the original array and, potentially, the new result array. In order to write that expression, you need to know the names of the result and index variable. That's why it's a macro that lets you specify variable names. Does that help?
jay vas
Ranch Hand

Joined: Aug 30, 2005
Posts: 407
Thanks --- Yeah that helps...

.... But if the point of amap is that its "in place", why do you need to specify two arrays ? In place algorithms only need one location to store the data, by their very definition....

I could elaborate, but I think you see where I'm going with this ----
Sean Corfield
Ranch Hand

Joined: Feb 09, 2011
Posts: 261
    
    5

Presumably so it leaves the original array unchanged after the map operation?

With aset / aget and loop / recur you could always mutate an array in place - so amap is more of a convenience to perform a transformation from one array to a new array.

This is one of those areas where Clojure's Java interop peeks thru in a slightly strange ways that don't quite sit well alongside Clojure's own immutable data structures
 
 
subject: Amap idx