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.

有帮助吗?

解决方案

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

其他提示

The shortest Way to write it is

*2
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top