Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.
Bug 347529 - Support return values for loop-expressions
Summary: Support return values for loop-expressions
Status: CLOSED WORKSFORME
Alias: None
Product: TMF
Classification: Modeling
Component: Xtext (show other bugs)
Version: unspecified   Edit
Hardware: PC Mac OS X - Carbon (unsup.)
: P3 enhancement (vote)
Target Milestone: ---   Edit
Assignee: Project Inbox CLA
QA Contact:
URL:
Whiteboard:
Keywords:
Depends on:
Blocks:
 
Reported: 2011-05-27 18:12 EDT by Moritz Eysholdt CLA
Modified: 2012-11-21 05:57 EST (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Moritz Eysholdt CLA 2011-05-27 18:12:23 EDT
Xtend2 supports while-loops and foreach-loops. Both loops are expressions, but they doen't have return values. To allow an even more declarative programming style, it would be nice to allow return values. I think it's a good idea to distinguish between single-value return values and multi-value return values. Actually, these are loop-canceling expressions and expressions that don't cancel loop execution.


Example 1: Use "break" for loops like "return" for methods:
----
val result = for(i:integerList) { if(i == 5) { break "foo" } }
----
expect result to be "foo" if the list contains the number 5, void otherwise.

----
val result = for(i:integerList) { if(i == 5) { break "foo" } } default "bar"
----
expect result to be "foo" if the list contains the number 5, "bar" otherwise.


Example 2: initalize a list within a loop:

---
val result = newArrayList() : for(i:integerList) { if(i < 5) { add(i) }
---
expect result to contain all values from integerList that are smaller than 5.

another syntax for the same expression might be:
---
val result = for(i:integerList -> newArrayList()) { if(i < 5) { add(i) }
---

potential problem: the returned list is an implicit receiver and I'm not sure if we do or want to suport this (I like it).

The same kinds of concepts can be applied to while-loops.
Comment 1 Knut Wannheden CLA 2011-05-28 11:36:49 EDT
Maybe I've missed the point, but isn't it always possible to achieve the same result using higher order functions like filter(), map(), reduce(), and fold()? E.g.

val result = if (integerList.exists(e|e == 5)) "foo"
val result = if (integerList.exists(e|e == 5)) "foo" else "bar"
val result = integerList.filter(e|e<5).map(e|e)

I have probably missed the point, but IMHO using higher order functions is even more declarative. In fact I wouldn't use for loops as much in Java if higher order functions were as concise as in Xtend2.
Comment 2 Sven Efftinge CLA 2012-11-21 05:57:40 EST
see comment 1