score:1
The problem is that padTo actually fills the list up to a given size. So the first time it works with 4 elements padded, but the next time you'll have to add the actual length of the curent list - hence:
def decompress(tList: List[Tuple2[Int,Any]]): List[Any] = {
val newList = tList.foldLeft(List[Any]())((b,a) => {
b.padTo(a._1+b.length, a._2)
})
newList
}
score:0
This works:
scala> testList.foldLeft(List[Char]()){ case (xs, (count, elem)) => xs ++ List(elem).padTo(count, elem)}
res7: List[Char] = List(a, a, a, a, b, c, c, a, a, d, e, e, e, e)
The problem actually is that when you say b.padTo(padCount, padElement)
you use always the same list (b
) to fill up the elements. Because the first tuple data generate the most elements nothing is added in the next step of foldLeft
. If you change the second tuple data you will see a change:
scala> val testList = List(Tuple2(3, 'a'), Tuple2(4, 'b'))
testList: List[(Int, Char)] = List((3,a), (4,b))
scala> testList.foldLeft(List[Char]()){ case (xs, (count, elem)) => xs.padTo(count, elem)}
res11: List[Char] = List(a, a, a, b)
Instead of foldLeft
you can also use flatMap
to generate the elements:
scala> testList flatMap { case (count, elem) => List(elem).padTo(count, elem) }
res8: List[Char] = List(a, a, a, a, b, c, c, a, a, d, e, e, e, e)
By the way, Tuple(3, 'a')
can be written (3, 'a')
or 3 -> 'a'
Note that padTo
doesn't work as expected when you have data with a count of <= 0:
scala> List(0 -> 'a') flatMap { case (count, elem) => List(elem).padTo(count, elem) }
res31: List[Char] = List(a)
Thus use the solution mentioned by Garret Hall:
def decompress[A](xs: Seq[(Int, A)]) =
xs flatMap { case (count, elem) => Seq.fill(count)(elem) }
scala> decompress(List(2 -> 'a', 3 -> 'b', 2 -> 'c', 0 -> 'd'))
res34: Seq[Char] = List(a, a, b, b, b, c, c)
scala> decompress(List(2 -> 0, 3 -> 1, 2 -> 2))
res35: Seq[Int] = List(0, 0, 1, 1, 1, 2, 2)
Using a generic type signature should be referred in order to return always correct type.
score:1
You could do your decompress like this:
val list = List(Tuple2(4, 'a'), Tuple2(1, 'b'), Tuple2(2, 'c'), Tuple2(2, 'a'), Tuple2(1, 'd'), Tuple2(4, 'e'))
list.flatMap{case (times, value) => Seq.fill(times)(value)}
Source: stackoverflow.com
Related Query
- padTo error inside a foldLeft
- Confused by foldLeft error (both in Eclipse and REPL)
- Error handling with Try match inside an udf - and log row where it failed
- About an error accessing a field inside Tuple2
- When I use Binding.scala, I got the error `each instructions must be inside a SDE block`, how can I fix this?
- Error trying to run Scala Application inside Eclipse
- Type variance error in Scala when doing a foldLeft over Traversable views
- Compile time error in scala Map while I put an object inside value
- How to Convert Seq to Json using Circe inside a function - keep getting "implicit value not found" error
- Scala Implicit class (using implicits inside implicit class) - Not a member of Int error
- Scala StackOverflow error while creating the object of the class inside class
- Shapeless: foldLeft on hlist compilation error
- Type mismatch error with foldLeft method in Scala
- error starting 'sbt' inside project directory
- How to use condition inside foldLeft in spark Scala?
- Returning Error for Invalid Parse inside of `rep`
- Play-json: Error on updating an object attribute inside an array
- Why doesn't the stream continue if the error occurs inside the Source
- Type mismatch error when trying to format float variable inside string interpolator
- Calling Method inside a method giving a type mismatch error Scala
- `Future.failed` inside of `transformWith[Array[Byte]]` gives a compiler error
- scala Error handling inside a function
- Error on creating local dataframe inside spark mapGroups function
- Error : RDD transformations and actions can only be invoked by the driver, not inside of other transformations
- Spark java.lang.NullPointerException Error when filter spark data frame on inside foreach iterator
- Scala: Error in += for ArrayBuffer inside function
- difference between foldLeft and reduceLeft in Scala
- sbt-assembly: deduplication found error
- Spark - Error "A master URL must be set in your configuration" when submitting an app
- Class broken error with Joda Time using Scala
More Query from same tag
- How to run a Play 2.2.1 project from Scala IDE?
- What is the most recommended way to capture TCP Server's output to an Akka Stream queue?
- can not show result in scala using println
- Cannot run a Scala program in IntelliJ
- Can't print RDD content with take() action
- Scala extreme destructuring?
- Disable ALL hints in IntelliJ IDEA
- Creating custom DOM events with scalajs
- Merging multiple maps and keeping the values in a list
- impicit Ordering and covariance
- How to write a custom Transformer in MLlib?
- Scala - Join dataframes relation 1 to n
- Enable Task Tags in Scala IDE for Eclipse
- Scala Option map to another Option
- Can't install nb-scala on NetBeans 7.4rc1
- Navigating through Sequence of DataFrames in Scala
- Complex Json schema into custom spark dataframe
- Scala/Java Project not finding Dependencies during Maven compile
- Printing query results from Mongodb in Scala using mongo-scala-driver
- Convert Directive1[Option[String]] to String scala
- Implicit in Scala 'for' enumerator?
- Working with Lift XHTML/HTML in Netbeans
- Out of memory error when writing out spark dataframes to parquet format
- Scala Play framework enable only certain filters
- What is the ?= operator in the Play Framework?
- How do I update dependencies in a Google Cloud function without deleting and redeploying?
- Passing scala slick table in the akka actor message
- Finding the implicit value for Json in play
- Parallel function to perform element wise operations on a collection in Scala
- Run Cypher for Apache Spark examples (CAPS)