Fun problem with Scala.

Here's a fun problem to solve with Scala.

Given N lists, dedupe them with the following rules. Go through the first list, dedupe it. Go through every consecutive list and only leave items which are not in a previous list and also take care of removing duplicates.

The challenge here is to do this without using vars and by only using vals. If you use vars, the solution is trivial.

The solution to this problem is using foldLeft. foldLeft essentially gives you a way to operate on the elements of a list while aggregating some state. The state you aggregate is the elements you've already seen and the current result. The final solution looks like this:

And while we're at it, let's see how the C++ solution looks like, for comparison. My C++ might be a bit rusty, but the result is longer.