ryeguy
ryeguy

Reputation: 66891

How to do something like this in Scala?

Sorry for the lack of a descriptive title; I couldn't think of anything better. Edit it if you think of one.

Let's say I have two Lists of Objects, and they are always changing. They need to remain as separate lists, but many operations have to be done on both of them. This leads me to doing stuff like:

//assuming A and B are the lists
A.foo(params)
B.foo(params)

In other words, I'm doing the exact same operation to two different lists at many places in my code. I would like a way to reduce them down to one list without explicitly having to construct another list. I know that just combining lists A and b into a list C would solve all my problems, but then we'd just be back to the same operation if I needed to add a new object to the list (because I'd have to add it to C as well as its respective list).

It's in a tight loop and performance is very important. Is there any way to construct an iterator or something that would iterate A and then move on to B, all transparently? I know another solution would be to construct the combined list (C) every time I'd like to perform some kind of function on both of these lists, but that is a huge waste of time (computationally speaking).

Upvotes: 1

Views: 665

Answers (2)

Eastsun
Eastsun

Reputation: 18869

I'm not sure if I understand what's your meaning. Anyway, this is my solution:

scala> var listA :List[Int] = Nil
listA: List[Int] = List()

scala> var listB :List[Int] = Nil
listB: List[Int] = List()

scala> def dealWith(op : List[Int] => Unit){ op(listA); op(listB) }
dealWith: ((List[Int]) => Unit)Unit

and then if you want perform a operator in both listA and listB,you can use like following:

scala> listA ::= 1
scala> listB ::= 0
scala> dealWith{ _ foreach println }
1
0

Upvotes: 2

Walter Chang
Walter Chang

Reputation: 11606

Iterator is what you need here. Turning a List into an Iterator and concatenating 2 Iterators are both O(1) operations.

scala> val l1 = List(1, 2, 3)
l1: List[Int] = List(1, 2, 3)

scala> val l2 = List(4, 5, 6)
l2: List[Int] = List(4, 5, 6)

scala> (l1.iterator ++ l2.iterator) foreach (println(_)) // use List.elements for Scala 2.7.*
1
2
3
4
5
6

Upvotes: 4

Related Questions