Effective Haskell: list-comprehension version of partyBudget has an error if food is duplicated (page 90)

(I may be overthinking corner cases for a little example program)

If you pass in a list of guests with a duplicated food, like [(“Alice”, “hamburger”), (“Bob”, “ice cream”), (“Chris”, “ice cream”)], and a willEat where both Bob and Chris will eat ice cream, then the total number of ice creams bought is 4, not 2, because there are two entries for “ice cream” in the food list.

A way to fix it would be to change the line of the program to:
food ← nub $ map snd guests

1 Like

Another good catch. Some of these are tricky because if you dig too much into the edge cases the example starts becoming dominated by edge case handling rather than the idea that’s being explained, but I think there’s probably a good way to handle this one.

Unfortunately, nub is probably best avoided since it’s very slow, and using it on even moderately sized lists can be really bad for performance, so it’s probably best to avoid teaching people to use it.

1 Like

I didn’t know nub was slow. TIL, thanks!

(and you have my sympathies on navigating the balance between edge-case handling and useful explanation of the main point – it seems hard!)