Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How map function does sorting in scala

The following code snippet

val keys=List(3,2,1,0)
val unsorted=List(1, 2, 3, 4)
val sorted =keys map unsorted

does sorting based on the keys.

Normally, map method takes a lambda and apply it to every element in the source. Instead the above code takes a list and does a sorting based on the index.

What is happening in this particular situation?

like image 289
Hariharan Avatar asked May 25 '26 11:05

Hariharan


1 Answers

List is a partial function that goes from its indices to its values. You could look at it like this:

scala> List(3,2,1,0) map (i => List(1,2,3,4)(i))
res0: List[Int] = List(4, 3, 2, 1)

to verify

scala> val f: Int => Int = List(1, 2, 3, 4)
f: Int => Int = List(1, 2, 3, 4)
like image 131
Łukasz Avatar answered May 28 '26 07:05

Łukasz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!