Scala Map List vs mapConserve

I am trying to understand mapConserve, which is called "Like xs map f, but returns xs unchanged if the function f displays all the elements in itself" from List . However, it throws an error.

def map [B] (f: (A) ⇒ B): List[B] def mapConserve (f: (A) ⇒ A): List[A] def mapConserve [B >: A <: AnyRef] (f: (A) ⇒ B): List[B] scala> list map (x=>x) res105: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> list mapConserve (x=>x) <console>:12: error: inferred type arguments [Int] do not conform to method mapConserve type parameter bounds [B >: Int <: AnyRef] list mapConserve (x=>x) ^ 

MapConserve code must satisfy function (A) => A. If not, it must still satisfy function (A) => B, since type A can be a subtype and a supertype of itself. Please enlighten me mapConserve goal and errors.

+6
source share
1 answer

Actually, mapConserve is defined as

 def mapConserve[A <: AnyRef](xs: List[A])(f: A => A): List[A] def mapConserve[B >: A <: AnyRef](f: A => B): List[B] 

therefore A must be a subtype of AnyRef . Int is a subtype of AnyVal that results in an error.

 scala> val l = List("foo", "bar", "baz") l: List[java.lang.String] = List(foo, bar, baz) scala> l.mapConserve(_.toUpperCase) res4: List[java.lang.String] = List(FOO, BAR, BAZ) scala> l.mapConserve(identity) res5: List[java.lang.String] = List(foo, bar, baz) 

Update:

The only difference between map and mapConserve , as described in scaladoc :

Creates a new list, applying the function to all elements of this list. Like xs map f, but returns xs unchanged if the function f maps all elements to itself (as defined by eq).

 scala> val xs = List.fill(1000000)("foo") xs: List[java.lang.String] = List(foo, foo,...) scala> xs.map(identity) eq xs res48: Boolean = false scala> xs.mapConserve(identity) eq xs res49: Boolean = true 

And xs mapConserve identity about five times faster in my simple test.

+18
source

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


All Articles