List returned from map method executes transformation on every access

34 views
Skip to first unread message

Wes

unread,
Apr 15, 2013, 8:23:09 AM4/15/13
to xtend...@googlegroups.com

Hi,

c.getAndIncrement is being executed for every access in the following code, i.e. this will print
0
1
2

I would expect the expression to be evaluated once during the map and not on access.

        val c = new AtomicInteger
        val m = #[ 0 ].map [ c.getAndIncrement ]
        println(m.get(0))
        println(m.get(0))
        println(m.get(0))

The result is the same if map is called on other types, e.g. (0 ..< 1) instead of #[ 0 ].

-Wes


Sebastian Zarnekow

unread,
Apr 15, 2013, 8:26:49 AM4/15/13
to xtend...@googlegroups.com
Hi Wes,

this works as designed and is described in the Javadoc:

Returns an iterable that performs the given transformation for each element of original when requested. The mapping is done lazily. That is, subsequent iterations of the elements in the iterable will repeatedly apply the transformation. That is, subsequent iterations of the elements in the list will repeatedly apply the transformation. 

#map returns a view on the original list / iterable. This allows for composition of various mappings / operations, e.g. filter without copying the complete list.
If you want a stateful representation of the mapping, you may use 

val copy = newArrayList
copy += list.map[..]

Best regards,
Sebastian


--
You received this message because you are subscribed to the Google Groups "Xtend Programming Language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to xtend-lang+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Wes

unread,
Apr 15, 2013, 8:52:31 AM4/15/13
to xtend...@googlegroups.com

Hi,

I see, would it be useful to have a stateful map method in the standard library (although it's easy enough to write one as an extension method)?

After working in scala, this was a little surprising.

Thanks,
Wes

Vito Impagliazzo

unread,
Apr 22, 2013, 12:41:49 PM4/22/13
to xtend...@googlegroups.com
try
val m = #[ 0 ].map [ c.getAndIncrement ].toList

this then copies all elements in a fresh new list, so you won't worry about havin g it executed again.

best
Vito
Reply all
Reply to author
Forward
0 new messages