[groovy-user] lists, ranges and generators

3 views
Skip to the first unread message

Russel Winder

unread,
18 Dec 2011, 04:14:1718/12/2011
to Groovy Users
I idly typed in:

println ( sum ( 1i..1000000000i ) )

to the GroovyConsole expecting it to work. My reasoning is that an
IntRange is a generator and not a data structure therefore things work.
Or not...


java.lang.OutOfMemoryError: Java heap space
at java.util.AbstractCollection.toArray(AbstractCollection.java:136)
at groovy.lang.MetaClassImpl.tryListParamMetaMethod(MetaClassImpl.java:1062)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:905)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:883)


Now you don't get this problem with Python:

print ( sum ( xrange ( 1000000000 ) ) ) # Python 2
print ( sum ( range ( 1000000000 ) ) ) # Python 3

both result in 499999999500000000 -- admittedly after a few seconds of
churning.

xrange in Python 2 and range in Python 3 is a generator, i.e. range
( 1000000000 ) represents the sequence ( 0 , 999999999 ) without
creating an actual data structure. Generators are iterable.

I had assumed that IntRange provided an iterable generator rather than
constructing a data structure, but this appears not to be the case. Can
I suggest that Groovy needs this concept to deal with big numbers of
things, and that 2.0.0 would be a good time to add stuff?

Or have I missed something... (always likely).

--
Russel.
=============================================================================
Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel...@ekiga.net
41 Buckmaster Road m: +44 7770 465 077 xmpp: rus...@russel.org.uk
London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder

signature.asc

Guillaume Laforge

unread,
18 Dec 2011, 11:33:4718/12/2011
to us...@groovy.codehaus.org
Which sum() method are you calling here?

--
Guillaume Laforge
Groovy Project Manager
Head of Groovy Development at SpringSource
http://www.springsource.com/g2one

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email


Reply all
Reply to author
Forward
0 new messages