Avoiding partial functions

From HaskellWiki
Revision as of 11:23, 5 June 2012 by Lemming (talk | contribs) (first examples: head, tail, !!)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

There are several partial functions in the Haskell standard library. If you use them, you always risk to end up with an undefined. In this article we give some hints how to avoid them, leading to code that you can be more confident about.

For a partial function f the general pattern is: Whereever we write "check whether x is in the domain of f before computing f x", we replace it by combination of check and computation of f.

head, tail

You should replace

if null xs
  then g
  else h (head xs) (tail xs)


case xs of
   [] -> g
   y:ys -> h y ys


You should replace

if k < length xs
  then xs!!k
  else y


case drop k xs of
   x:_ -> x
   [] -> y

This is also more lazy, since for computation of length you have to visit every element of the list.