Why Ruby?

retard re at tard.com.invalid
Wed Dec 15 14:18:23 PST 2010


Wed, 15 Dec 2010 22:23:35 +0100, Jacob Carlborg wrote:

> On 2010-12-14 22:04, Nick Sabalausky wrote:
>> "Jacob Carlborg"<doob at me.com>  wrote in message
>> news:ie8f5f$o6e$1 at digitalmars.com...
>>>
>>> Probably not, but, for example, Scala allows very compact delegate
>>> literals:
>>>
>>> Array(1, 2, 3, 4, 5).select(_>  3).collect(_ * _)
>>>
>>> Or more verbose:
>>>
>>> Array(1, 2, 3, 4, 5).select((x) =>  x>  3).collect((x, y) =>  x * y)
>>>
>>> I'm not 100% sure I that the syntax is correct.
>>>
>>>
>> I'd be surprised if the first one is correct, because that "collect(_ *
>> _)" would seem highly limited (how would you use the same value twice,
>> or use just the second value, or use them in reverse order?).
> 
> I guess for anything more complicated you would have to use the =>
> syntax. BTW, I just verified that this works:
> 
> Array(1, 2, 3, 4, 5).sortWith(_ > _)

The first instance of _ (from left to right) is replaced with the first 
element of the parameter tuple, the second with second element, etc.

This is actually very useful since many lambdas only use 1-2 parameters. 
It has its limitations. For example referring to the same parameter 
requires a named parameter or some other hack. Combined with Haskell 
style partial application this allows stuff like:

Array(1, 2, 3, 4, 5).foreach { println }

Array(1, 2, 3, 4, 5).filter(2 <)


More information about the Digitalmars-d mailing list