In the context of functional programming, what are 'total' functions and 'partial' functions?

I'm not finding via Google any explanation that my brain can grasp. Can someone explain this, and if possible, give an example of each using either pseudocode or C#?

The term 'total' function was introduced to me in the comments section of this question. The comment is:

when you work with total functions, you can compose them with other functions and use them in higher order functions without worrying about error results "not encoded in the type", i.e. exceptions. – Andres F.

I'm intrigued by this comment.

• I think this is not a real dupe. This question is about concepts on functional programming (see tag). The referred question is about algorithmic terminology. The wording of the other question is very different and only remotely connected to this one. OP could not have recognized his interest therein. It appears that one answer explains what a total function is, and another refers to total and partial functions without elaborating further. But the fact of having some overlapping elements in the answer is not sufficient IMO for making it a dupe. Oct 29 '16 at 22:37
• This has a community close on it, meaning the question author closed it as a duplicate. Yet there are four reopen votes? Madness!
– user22815
Nov 4 '16 at 19:21
• @Snowman The question author is not the only one who gets to decide :) Nov 4 '16 at 19:50

Here's a reasonable definition from the Haskell wiki:

A total function is a function that is defined for all possible values of its input. That is, it terminates and returns a value.

A partial function is a function that is not defined for all possible input values; in some cases instead of returning a value, it may never return at all (think infinite cycles), throw an exception (which usually states "this is undefined for this input value" or "unexpected input" or whatever) or simply crash the system.

A well-known example of a partial function is the integer division, a divided by b: it's not defined when b is zero!

Another example is head, the Haskell function that takes the first element of a list, which throws an error if the list is empty! Something like this:

head :: [a] -> a  // this is the signature
head (first : rest) = first
head _ = ... // This is an error! What is the first element of the empty list?

Partial functions like head unfortunately exist in Haskell for historical reasons. Note it can be made total like this:

headMaybe :: [a] -> Maybe a
headMaybe (first : rest) = Just first