[Melbourne-pm] pmap execution time (was I <3 map & grep too)

Toby Corkindale toby.corkindale at strategicdata.com.au
Thu Nov 10 21:34:34 PST 2011

On 11/11/11 16:03, Toby Corkindale wrote:
> The code is:
> val foo = (1 to 8).toList.par.map(_ => 39)
> foo map dumb_fib foreach println
> // or you can write:
> // foo.map(dumb_fib).foreach(println)

Someone asked about the alternative ways to write that line, so I 
thought I'd explain here in case others were curious.

Scala, like Perl, has some shortcuts in the language.
The following lines are all equivalent:

The long way:
   foo.map(x => dumb_fib(x)).foreach(y => println(y))

Shortened by using _ (it's like $_ in perl):

If you only have one parameter, you don't need to even use _, it'll use 
it by default:

And if you only have one parameter to a function, you can skip the 
parentheses and it'll just take the next symbol as the parameter. You 
can also leave the dots out too:
   foo map dumb_fib foreach println

This last form looks a bit more confusing to me than the previous one. 
However if you're building DSLs, you can make stuff read a bit more like 
natural language.


More information about the Melbourne-pm mailing list