Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Scala provide both multiple parameters lists and multiple parameters per list? [duplicate]

Multiple parameters lists, e.g. def foo(a:Int)(b:Int) = {} and multiple parameters per list, e.g. def foo(a:Int, b:Int) = {} are semantically equivalent so far as I can tell, and most functional languages have only one way of declaring multiple parameters, e.g. F#.

The only reason I can figure out for supporting both these styles of function definitions is to allow syntax-like language extensions using a parameter list that has only one parameter in it.

def withBufferedWriter(file: File)(block: BufferedWriter => Unit) 

can now be called with the syntax-looking

withBufferedWriter(new File("myfile.txt")) { out =>   out write "whatever"   ... } 

However, there could be other ways of supporting the use of curly braces without having multiple parameter lists.

A related question: why is the use of multiple parameter lists in Scala called "currying"? Currying is usually defined as a technique for making an n-ary function unary for the sake of supporting partial application. However, in Scala one can partially apply a function without making a "curried" (multiple parameter lists with one param each) version of the function.

like image 454
Yuvi Masory Avatar asked Jan 13 '11 19:01

Yuvi Masory


People also ask

Why currying is useful in scala?

Advantages of Currying Function in Scala One benefit is that Scala currying makes creating anonymous functions easier. Scala Currying also makes it easier to pass around a function as a first-class object. You can keep applying parameters when you find them.

What does => mean in scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

What is a parameter in scala?

Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called.

What is partially applied function in scala?

The Partially applied functions are the functions which are not applied on all the arguments defined by the stated function i.e, while invoking a function, we can supply some of the arguments and the left arguments are supplied when required.


1 Answers

It makes you able to do e.g.:

scala> def foo(as: Int*)(bs: Int*)(cs: Int*) = as.sum * bs.sum * cs.sum foo: (as: Int*)(bs: Int*)(cs: Int*)Int  scala> foo(1, 2, 3)(4, 5, 6, 7, 9)(10, 11) res7: Int = 3906 
like image 62
Knut Arne Vedaa Avatar answered Oct 17 '22 11:10

Knut Arne Vedaa