Lambda syntax, etc

hsyl20 hsyl20 at yahoo.fr
Fri Feb 6 09:27:47 PST 2009


> > You can use several "_", for instance:
> > scala>  val a = List(10,5,2,48,75,84,96,85,3,21,52)
> > a: List[Int] = List(10, 5, 2, 48, 75, 84, 96, 85, 3, 21, 52)
> >
> > scala>  val b = a reduceLeft (_ + _)
> > b: Int = 481
> >
> > The only problem is if you want to change arg order. In this case you have to use named parameters.
> > scala>  val b = a reduceLeft (_ - _)
> > b: Int = -461
> >
> > scala>  val b = a reduceLeft ((a,b) =>  b - a)
> > b: Int = -5
> >
> > Cheers
> > Sylvain
> 
> this seems counter-intuitive to me. Nemerle uses this syntax for 
> currying which seems to me a much better meaning to this syntax.
> for example ( using D like syntax):
> 
> int func (string a, char b, int c) { ... }
> auto a = func( "hello", _, 8);
> 
> the above is syntax sugar for:
> 
> auto a = int(char b) { return func("hello", b, 8); };

"_" is used for currying in Scala too.

scala> def func (a:Int)(b:String) = {} 
func: (Int)(String)Unit                

Unit is the same thing as void in Scala.

scala> func (5) _
res7: (String) => Unit = <function>

scala> func (_:Int) ("blah")
res15: (Int) => Unit = <function>

scala> func (_) ("blah")
<console>:6: error: missing parameter type for expanded function ((x$1) => func(x$1)("blah"))
       func (_) ("blah")

(I don't know why I have to specify "Int" type. Maybe it has been corrected in the last versions.)

Cheers,
Sylvain



More information about the Digitalmars-d mailing list