145

2
+1  Q:

## 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 `List`s 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).

+1  A:

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

+3  A:

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
``````
Minor correction. To get the iterator: (l1.elements ++ l2.elements). The Iterator solution can't be used with mutable lists though, as the OP apparently wants. Also, the Iterator in Scala library seems to be one-time-use only. You can't rewind it and reuse it. Yet, upvoting cause, iterator is the way to go here, but probably not the scala library version.
This works great, thanks. I did use HRJ's idea though (elements).
@HRJ @ryeguy that's why the comment following the foreach statement ;-) List.elements is deprecated in Scala 2.8.0, use iterator instead.