user377628
user377628

Reputation:

Is there a way I can write this Haskell code in Scala?

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.

Upvotes: 4

Views: 180

Answers (2)

user unknown
user unknown

Reputation: 36250

The shortest Way to write it is

*2

Upvotes: 1

Eastsun
Eastsun

Reputation: 18869

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

Upvotes: 8

Related Questions