bbaron (61) [Avatar] Offline
#1
I believe your solution to finding the oldest person working in IT has a bug (p. 124 of MEAP v2). Given the example list, the correct result is returned, but in the general case, it's possible to return the incorrect result, if the head of the list contains a non-IT employee who is older than than oldest IT employee. To produce the bug, I did Employee("Joe", 99, "Sales") :: employees. Joe was returned as the "oldest IT employee."

The way I solved it is to save the filtered list in a val called itEmps. Then I call itEmps.tail.foldLeft(itEmps.head) to ensure the fold is seeded with a valid employee.
aslam.khan (50) [Avatar] Offline
#2
Re: Coffee Break: data transformations
Thank you for that feedback. And well spotted too smilie

Your solution is valid, and I suspect that there is a more succinct solution with list comprehensions (Scala's for-expressions) which is the topic of the next chapter. I will attempt to recreate that example as a list comprehension to illustrate the difference.
seamusv (3) [Avatar] Offline
#3
Re: Coffee Break: data transformations
Here is my solution:

employees
.filter(_.department == "IT")
.maxBy(_.age)

res0: Employee = Employee(Mary,32,IT)
aslam.khan (50) [Avatar] Offline
#4
Re: Coffee Break: data transformations
maxBy() ... sneaky smilie

Did you try it without maxBy()? If so, please share your solution.
seamusv (3) [Avatar] Offline
#5
Re: Coffee Break: data transformations
I suppose another option would be to apply the filter twice... once for the list of IT employees and the other to seed the foldLeft:

employees
.filter(_.department == "IT")
.foldLeft(employees.filter(_.department == "IT"smilie.head)((a, b) => if (a.age > b.age) a else b)

But these solutions are assuming there is at least one IT employee otherwise they will cause an exception.
seamusv (3) [Avatar] Offline
#6
Re: Coffee Break: data transformations
Here is another solution... but it is using reduce.

employees
.filter(_.department == "IT")
.reduce((a, b) => if (a.age > b.age) a else b)