4

I'm going through a few functional programming languages, learning things of interest, and I'm looking at Scala now. What I'm trying to do is figure out the simplest way to write a function called double which take one argument and doubles it. What I've come up with so far is:

def double = (x:Int) => x*2

or

def double(x:Int) = x*2

This works, but I'm looking for the simplest way. In Haskell, I could simply do this:

double = (*2)

Because it's a partially applied function, there's no need to name the variable or specify any types (I'm sure the * function takes care of that). Is there a similar way to do this using Scala? I've tried a few, especially using _ instead of x, but none seemed to work.

hammar
  • 138,522
  • 17
  • 304
  • 385

2 Answers2

8

How about this:

val double = (_: Int) * 2

Note Here double is a Function rather than a method. In your first example, you have defined a method named double with return type of Function. In your second example, your just have defined a method. Function is different from method in Scala.

In case the compiler can get the type information, we can write the Function even simple:

scala> def apply(n: Int, f: Int => Int) = f(n)
apply: (n: Int, f: Int => Int)Int

scala> apply(10, 2*)
res1: Int = 20

scala> apply(10, 100+)
res2: Int = 110
Eastsun
  • 18,526
  • 6
  • 57
  • 81
  • "Function is different from method in Scala." A seemingly very important fact that I was clueless of. Thanks for clearing that up. –  Jun 08 '13 at 03:23
  • Whoa. I never knew we could pass `2*` that way. Thanks. – Jatin Jun 08 '13 at 07:33
1

The shortest Way to write it is

*2
user unknown
  • 35,537
  • 11
  • 75
  • 121
  • How can this be set to a val? I tried `val double = *2`, but it didn't like that. –  Jun 08 '13 at 16:50
  • No, you don't write `val double = ` at all, just * 2 where you need it. It means the same, is directly understandable and avoids confusion with java.lang.Double and such. – user unknown Jun 08 '13 at 17:37