Is there a way to write this Haskell code in Scala?

I look at several functional programming languages, learning interesting things, and now I look at Scala. What I'm trying to do is the easiest way to write a function called double that takes one argument and doubles it. So far I have come to the following:

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

or

 def double(x:Int) = x*2 

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

 double = (*2) 

Since this is a partially applicable function, there is no need to specify a variable or indicate any types (I am sure that the function * will take care of this). Is there a similar way to do this with Scala? I tried several, especially using _ instead of x , but no one worked.

+4
source share
2 answers

How about this:

 val double = (_: Int) * 2 

Note Here double is Function , not method . In the first example, you defined a method called double with a return type of Function . In your second example, you simply defined a method . Function is different from method in Scala.

If the compiler can get type information, we can write Function even simply:

 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 
+8
source

The shortest way to write is

 *2 
+1
source

Source: https://habr.com/ru/post/1485138/


All Articles