I’m trying to learn Scala (2.10). In this exercise, I have a case class:
case class Entry(name: String, version: String) { }
I have two sequences of such objects sorted by their name attribute:
S1 = E1, E3, E4
S2 = F1, F2, F4
I want to construct a new sequence:
S3 = (E1, F1), (None, F2), (E3, None), (E4, F4)
pairing them by their name attribute, preferrably without having to iterate more than once over each list.
All my solutions for this problem becomes extremely imperative in style (e.g. conditionally incrementing two integers and using .get()). I hope some kind soul can suggest a more functional approach.
You mean by their
versionattribute, judging from the example?You can use lists and recursion:
Essentially, you progress to the list comparing their heads, and taking both heads if the version is the same, or taking only the smaller one. You then recursively do the same for the tail of the lists. If one of the lists turns out to be empty, you just map the remaining elements of the other list into pairs of
Noneand the entry.