24

Let's create a value for the sake of this question:

val a = 1 :: Nil

now, I can demonstrate that the anonymous functions can be written in shorthand form like this:

a.map(_*2)

is it possible to write a shorthand of this function?:

a.map((x) => x)

my solution doesn't work:

a.map(_)
3
  • Doesn't make much sense, does it? It's just a NOP. Commented Dec 12, 2010 at 14:11
  • this is just an example. it can make some sense in context Commented Dec 12, 2010 at 14:21
  • 3
    This is a good example of the cases where the overuse (imho) of '_' sugar in Scala really makes it difficult for people to pick up the language. Commented Mar 3, 2013 at 21:29

3 Answers 3

43

For the record, a.map(_) does not work because it stands for x => a.map(x), and not a.map(x => x). This happens because a single _ in place of a parameter stands for a partially applied function. In the case of 2*_, that stands for an anonymous function. These two uses are so close that is very common to get confused by them.

Sign up to request clarification or add additional context in comments.

3 Comments

Actually the two usages are the same thing, "placeholder syntax." The spec doesn't use the phrase "partially applied"; the change log uses it only for m _ syntax; Programming in Scala uses it first for m _ and then for m(_). But f(_) is syntactically like if (_). "Partial applications" get help inferring the param type.
Hum, then I wonder why can't we have something like a val pFunc = a.map(_) ?
@SpiXel You can, but you need to specify pFunc's type. Not that map takes a function, so x in x => a.map(x) would be a function from Int to some type. There's no way to infer what type that would be, therefore, you need to specify the type for pFunc, at which point Scala will gladly accept that line.
24

Your first shorthand form can also be written point-free

a map (2*)

Thanks to multiplication being commutative.

As for (x) => x, you want the identity function. This is defined in Predef and is generic, so you can be sure that it's type-safe.

7 Comments

I think you mean commutative.
It's a pity that x=>x is four characters while identity is eight. This is why I never use identity.
@debilski This stuff isn't easy you know! Not when there's an 18 month-old fighting for access to the keyboard!
@Rex identity may be 8 letters, but it's still a single identifier and so is easier to parse (for humans and compilers alike)
@Rex the AST would beg to differ... and I still see my eye drawn to that arrow anyway :)
|
17

You should use identity function for this use case.

a.map(identity)

identity is defined in scala.Predef as:

implicit def identity[A](x: A): A = x 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.