Bug 489944 - new IntegerExtensions times (Ruby's) / timesRepeat (Smalltalk's)
Summary: new IntegerExtensions times (Ruby's) / timesRepeat (Smalltalk's)
Status: NEW
Alias: None
Product: Xtend
Classification: Tools
Component: Core (show other bugs)
Version: unspecified   Edit
Hardware: PC Linux
: P3 enhancement (vote)
Target Milestone: ---   Edit
Assignee: Project Inbox CLA
QA Contact:
URL:
Whiteboard:
Keywords:
Depends on:
Blocks:
 
Reported: 2016-03-18 10:25 EDT by Michael Vorburger CLA
Modified: 2016-03-18 10:25 EDT (History)
0 users

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Michael Vorburger CLA 2016-03-18 10:25:59 EDT
Hallo - what do you guys think about akin to Ruby's times and Smalltalk's timesRepeat, for:

    3.times [println("hiya!")]

introduce something like this somewhere, probably to org.eclipse.xtext.xbase.lib.IntegerExtensions:

    def static times(int iterations, Procedure0 action) {
        if (iterations < 0)
            throw new IllegalArgumentException('''Can't iterate negative («iterations») times.''')
        for (var i = 0; i < iterations; i++) // for (i : 0 ..< iterations)
            action.apply
    }

see also http://stackoverflow.com/questions/12126999/xtend-for-loop-support-and-adding-range-support/18065434#18065434

PS: I do understand that the following would be a tempting alternative, but would argue that the simpler above is better, because it works much better/is much less confusing when used inside other lambda expression (incl. e.g. inside the With operator).  Also one could suggest that someone using this syntax typically doesn't require access to the loop variable in the closure - if you do, then use the for with range alternative. Lastly note that according to http://stackoverflow.com/a/13667065/421602 Smalltalk's timesRepeat "is cleaner if you don't need the value of the index" so presumably is the former, not the latter - perhaps for good reason it's better NOT to do it like this:

    def static times(int iterations, IntConsumer action) {
        if (iterations < 0)
            throw new IllegalArgumentException('''Can't iterate negative («iterations») times.''')
	for (var i = 0; i < iterations; i++) // for (i : 0 ..< iterations)
            action.accept(i)
    }