Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala collections: why do we need a case statement to extract values tuples in higher order functions?

Tags:

scala

Related to Tuple Unpacking in Map Operations, I don't understand why do we need a case (that looks like a partial function to me) to extract values from tuple, like that:

arrayOfTuples map {case (e1, e2) => e1.toString + e2}

Instead of extracting in the same way it works in foldLeft, for example

def sum(list: List[Int]): Int = list.foldLeft(0)((r,c) => r+c)

Anyway we don't specify the type of parameters in the first case, so why do we need the case statement?

like image 379
eugen-fried Avatar asked Dec 16 '14 09:12

eugen-fried


People also ask

What is the use of tuples in Scala?

In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable. Tuples are especially handy for returning multiple values from a method.

Can we have variables of different types inside of a tuple Scala?

Thankfully, Scala already has a built-in tuple type, which is an immutable data structure that we can use for holding up to 22 elements with different types.

How do I return multiple values from a function in Scala?

You can return multiple values by using tuple. Function does not return multiple values but you can do this with the help of tuple.

What is the meaning of => 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 .


1 Answers

Because in Scala function argument lists and tuples are not a unified concept as they are in Haskell and other functional languages. So a function:

(t: (Int, Int)) => ...

is not the same thing as a function:

(e1: Int, e2: Int) => ...

In the first case you can use pattern matching to extract the tuple elements, and that's always done using case syntax. Actually, the expression:

{case (e1, e2) => ...}

is shorthand for:

t => t match {case (e1, e2) => ...}

There has been some discussions about unifying tuples and function argument lists, but there are complications regarding Java overloading rules, and also default/named arguments. So, I think it's unlikely the concepts will ever be unified in Scala.

like image 165
Jesper Nordenberg Avatar answered Oct 21 '22 20:10

Jesper Nordenberg