3

I have a task to traverse a sequence of tuples and based on last value in the tuple make 1 or more copies of a case class Item. I can solve this task with foreach and Mutable List. As I'm learning FP and Scala collections could it be done more functional way with immutable collections and high order functions in Scala?

For example, input:

List[("A", 2), ("B", 3), ...]

Output:

List[Item("A"), Item("A"), Item("B"),Item("B"),Item("B"), ...]
3
  • 2
    Why is this downvoted -2? It's an ok question. Commented Dec 17, 2014 at 18:47
  • Yay! It's in the positive. In fact I thought it was such a good question, I will use it my Scala classes. Tough to find a good simple flatMap based question and answer. Commented Dec 18, 2014 at 3:15
  • @DanielHinojosa wish people make comments after downwoting to figure out what's wrong with the question. Commented Dec 18, 2014 at 7:52

2 Answers 2

5

For each tuple flatMap using List.fill[A](n: Int)(elem: ⇒ A) which produces a List of elem n times.

scala> val xs = List(("A", 2), ("B", 3), ("C", 4))
xs: List[(String, Int)] = List((A,2), (B,3), (C,4))

scala> case class Item(s: String)
defined class Item

scala> xs.flatMap(x => List.fill(x._2)(Item(x._1)))
res2: List[Item] = List(Item(A), Item(A), Item(B), Item(B), Item(B), Item(C), Item(C), Item(C), Item(C))
Sign up to request clarification or add additional context in comments.

1 Comment

Great call with fill!
1

Using flatten for case class Item(v: String) as follows

myList.map{ case(s,n) => List.fill(n)(Item(s)) }.flatten

Also with a for comprehension like this,

for ( (s,n) <- myList ; l <- List.fill(n)(Item(s)) ) yield l

which is syntax sugar for a call to flatMap.

In addition to List.fill consider List.tabulate for initialising lists, for instance in this way,

for ( (s,n) <- myList ; l <- List.tabulate(n)(_ => Item(s)) ) yield l

1 Comment

nice solution with for comprehension! @enzyme

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.