On 9/15/11 10:24 PM, Michael Litchard wrote:
Someone commented on StackOverflow that pattern matching the first
element of a list was preferable to head. This makes sense
intuitively. Could someone articulate the reason why this is true?

(1) If you call (head xs) you are assuming that xs is non-empty. If xs is empty, then it will throw an exception. Which is a major issue because tracing down these exceptions is a headache for everyone involved. Whereas, if you do (case xs of [] -> ...; x:xs' -> ...) you explicitly handle the case of xs being empty. This also applies to things like tail and fromJust.


(2) Also, even if you know xs is non-empty because you called (null xs) or the like, you can do the case match once and use the results everywhere. Whereas, using head and tail means doing a case match every time they're called. This is an efficiency issue, and also applies to functions which won't throw exceptions: like fst and snd, instead of pattern matching the tuple.

--
Live well,
~wren

_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to