jastrachan | 1 Feb 08:30 2005
Picon

Re: thoughts on the closure/return/break/continue issue

On 31 Jan 2005, at 20:57, Juancarlo AƱez wrote:
> list.sum {|i|
>    if (i % 2 == 1) {
>      continue 0
>    }
>    i * i
> }
>
> That looks pretty bad! Why try to impose "continue" semantics on 
> closures?

To add an ability to 'return from block' like we can do with for & 
while loops

> What's wrong with:
>
>   list.inject(0) { sum, i | if (i % 2 == 1) sum else sum+i*i }
>
> Or
>
>   (list.findAll() {it%2 == 0}).inject(0) {it*it}

Absolutely nothing is wrong with that - those semantics are kept! The 
really really common use case of closures is exactly what you describe 
- the last expression is the value returned from the block.

The only use of 'continue' is if you have some complex logic (just like 
when you use continue in a for loop). i.e. its rarely used/needed but 
if you need it its the equivalent to 'return from block' just like 
continue is in Java. I rarely use continue myself much either; I tend 
to prefer to use if/else branching - and similarly we can do the same 
in groovy

The main idea behind this proposal was

* to define what return/break/continue mean inside all blocks in a 
consistent and straightforward way
* to add a 'return from block' which can be used in closures using a 
familiar syntax
* to avoid adding a new keyword for 'return from closure invocation'

Most people won't use this new continue syntax I suspect, but its there 
for completeness if its required. Most uses of closures tend to be as 
you describe, where the code is fairly simple and its pretty clear what 
the last expression is.

James
-------
http://radio.weblogs.com/0112098/


Gmane