Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why both transform and map methods in scala?

I'm having trouble understanding the difference between / reason for, for example, immutable.Map.transform and immutable.Map.map. It looks like transform won't change the key, but that just seems like a trivial variation of the map method. Am I missing something?

I was expecting to find a method that applied a function to the (key,value) of the map when/if that element was accessed (rather than having to iterate through the map eagerly with the map function). Does such a method exist?

like image 644
nairbv Avatar asked May 24 '13 14:05

nairbv


People also ask

What is map transformation in Scala?

Scala Map transform() method with exampleThe transform() method is utilized to transform the elements of the map into a mutable map. Method Definition: def transform(f: (K, V) => V): Map.this.type. Return Type: It transforms all the elements of the map and returns them into a mutable map.

What does map () do in Scala?

map() method is a member of TraversableLike trait, it is used to run a predicate method on each elements of a collection. It returns a new collection.

Are maps mutable in Scala?

Maps are classified into two types: mutable and immutable. By default Scala uses immutable Map. In order to use mutable Map, we must import scala.

How do I convert a list to map in Scala?

In Scala, you can convert a list to a map in Scala using the toMap method. A map contains a set of values i.e. key-> value but a list contains single values. So, while converting a list to map we have two ways, Add index to list.


2 Answers

You can do exactly that with mapValues. Here is the explanation from the docs:

def mapValues[C](f: (B) ⇒ C): Map[A, C]

Transforms this map by applying a function to every retrieved value.

f - the function used to transform values of this map.

returns - a map view which maps every key of this map to f(this(key)). The resulting map wraps the original map without copying any elements.

edit:

Although extending classes of the collection API is not often a good idea, it could work like this:

class LazilyModifiedMap[A,B,C](underlying: Map[A,B])(f: (A,B) => C) extends Map[A,C] {
  def get(key: A) = underlying.get(key).map( x => f(key, x))

  def iterator = underlying.iterator.map { case (k,v) => (k, f(k,v)) }

  def -(key: A) = iterator.toMap - key

  def +[C1 >: C](kv: (A,C1)) = iterator.toMap + kv
}
like image 74
drexin Avatar answered Sep 20 '22 06:09

drexin


If you only need the interface of PartialFunction, you can exploit the fact that Map inherits from PartialFunction:

val m = Map(1 -> "foo", 2 -> "bar")
val n = m.andThen(_.reverse)

n(1)  // --> oof
like image 23
0__ Avatar answered Sep 20 '22 06:09

0__