user1973190
user1973190

Reputation: 23

How do I create a function that takes any Seq[T,Int] and returns the original type of the Seq.

I'm having a hard time defining this question. I want to do something like this:

val list = List(("a",1), ("b",2))

private def shiftIndex[C <: Seq[_]](seq: C, amount: Int): C = {
  seq.map({ case (value, integer) => (value, integer + amount) })
}

shiftIndex(list,3) 

Should return

List(("a",4),("b",5)): List[String,Integer]

But it should work for the most general case:

  1. seq implements map (I know its not :Seq)
  2. seq is storing a tuple of anything and an Int.

Any links to resources the explains these concepts would be appreciated.

Upvotes: 2

Views: 161

Answers (1)

dhg
dhg

Reputation: 52681

import scala.collection.generic.CanBuildFrom
import scala.collection.GenTraversable
import scala.collection.GenTraversableLike

def shiftIndex[T, Repr](seq: GenTraversableLike[(T, Int), Repr], amount: Int)(
    implicit bf: CanBuildFrom[Repr, (T, Int), Repr]) = {
  seq.map { case (value, integer) => (value, integer + amount) }
}

shiftIndex(List(("a", 1), ("b", 2)), 3)     // List((a,4), (b,5))
shiftIndex(Set(("a", 1), ("b", 2)), 3)      // Set((a,4), (b,5))
shiftIndex(Map(("a", 1), ("b", 2)), 3)      // Map(a -> 4, b -> 5)

Though I might recommend a solution that's nicer looking and more generic. Here I enrich GenTraversable so that all traversable objects of pairs have a method mapVals that takes a function to be applied to the second part of the pair, and has a return type the same as the object it was run on:

class EnrichedWithMapVals[T, U, Repr](seq: GenTraversableLike[(T, U), Repr]) {
  def mapVals[R, That](f: U => R)(implicit bf: CanBuildFrom[Repr, (T, R), That]) = {
    seq.map { case (x, y) => (x, f(y)) }
  }
}
implicit def enrichWithMapVals[T, U, Repr](self: GenTraversableLike[(T, U), Repr]) = new EnrichedWithMapVals(self)

List(("a", 1), ("b", 2)).mapVals(_ + 3)     // List((a,4), (b,5))
Set(("a", 1), ("b", 2)).mapVals(_ + 3)      // Set((a,4), (b,5))
Map(("a", 1), ("b", 2)).mapVals(_ + 3)      // Map(a -> 4, b -> 5)

Upvotes: 5

Related Questions