Posts tagged haskell

Partial Functions in Haskell Prelude


Partial functions are functions that are not defined for all possible arguments of its specified type. The most common example of a partial function is . It has the innocent-looking type signature of fails when an empty list is given: Because of Haskell’s type erasure, doesn’t even know what the supplied type is, so there’s no way for it to return a value of type when there are no values in the list (besides the obvious fact that there are no values in the list). In Brent Yorgey’s CIS 194 Haskell course: head is a mistake! It should not be in the Prelude. Other partial Prelude functions you should almost never use include tail, init, last, and (!!). Haskell’s official wiki provides a complete list of partial functions in Prelude. Note that some of these functions are considered partial functions because they do not terminate if given an infinite list. Given all that, I think using something like is okay if composed with other functions that guarantee non-emptiness of the list, or if the function type signature is , a type class which guarantees a list with at least one element. For example, consider , a function which returns the last item in a list: In addition, consider , a function which, when given an value, returns a list of its constituent digits: A function like guarantees a non-empty list, and when combined with , we can get the last digit of an value: Or consider , which accesses an element in a list by index. If the index provided is too large, an exception is thrown: An idea is to wrap with the data type in a function like this: I’m surprised that such commonly used functions in the Prelude are so dangerous, so it’s good to pay attention when using them. Partial functions like are easy to replace with pattern matching, but others may be harder to supplant.