113Operation Lens
The last way to make a partial function total is to change the
meaning. This corresponds to the function name part of the
function signature.
Unfortunately, we can’t really change the meaning of di-
vision, so it’s a bad example. But I can share another one.
In JavaScript, there is an operator called delete that re-
moves a key/value from an object based on the key. Simi-
lar constructs exist in other languages. Some languages
(but not JavaScript) throw an error if you try to remove a
key that does not exist. Throwing an error in those cases is
a choice the designers made. Here is a signature for a func-
tional-style delete operation that throws errors if the key
does not exist.
function removeKey(object, key) //=> Object; throws error
function removeKey(object, key) //=> Object
One can see that the meaning of the name in English does
correspond to the behavior: How can you remove a key that
does not exist? If it doesn’t exist, removing it is meaningless,
so an error is thrown. It is a partial function.
We can make it total by changing the meaning of the
function. Instead of taking “remove key” literally, we could
interpret it as “ensure the key is not in the object.” If it’s not
in the object, there’s no work to do, so we can return the ob-
ject unchanged.
With that interpretation, the signature becomes:
I’ll leave implementing it (in a functional style) up to you.
Though at this point we are not concerned with production
implementations, writing a prototype implementation can
prove that it is possible.
Notice, however, that changing the meaning is the only
method that removes a burden. There are no errors to catch,
no extra return types to check for, and no conditions on the
arguments. It is not always possible to do—like in the case
of division—but when it is, we prefer it for making our code
simpler.
Partial to total: Change the meaning
Exercise