2 ms·
You're sort of asking the wrong question. The choice wasn't whether Maybe should implement length. Instead, there were two independent choices: should Maybe imp
by chowells 3y ago
You're sort of asking the wrong question. The choice wasn't whether Maybe should implement length. Instead, there were two independent choices: should Maybe implement Foldable, and should length be implemented in terms of Foldable?
For the first, the answer is absolutely yes. You really want things like traverse and sequence to work with Maybe, and that requires Maybe to implement Foldable (on the way to Traversable.) It's incredibly useful to be able to treat Maybe as just another container type.
Whether length should be in terms of Foldable, by contrast, is a much more debatable question. On one hand, it means a lot of unexpected things can have length called on them. (length (3,4)) evaluates to 1, for instance; that's just almost never useful, despite being completely logical. On the other hand, it's really awkward to need a different function to get the size of every container type. Especially when you can write a length function using just Foldable. And I think that's what led to that decision - if the standard library doesn't provide that definition, a whole bunch of other libraries will.
I'm still not sure about that decision. It's got some weird corner cases. There are some cases where it allows bugs, as the article points out. But at the same time, I have written code that is happy to use that degree of polymorphism, and does so safely because it allows the caller to choose the concrete type.
Maybe the real problem isn't the existence of those instances. Maybe the underlying issue is that you can use ad-hoc polymorphism at concrete types without knowing what those concrete types are. The article did touch on that aspect in its final paragraph, when it mentioned monomorphizing length at the call site. But even this feels like it could easily introduce more pain that it solves.
I've spent more time here talking about the potential issue than I ever have spent dealing with it in real software. Maybe it's just not that big of a deal.