Do you like to return None
from your functions from time to time to mark an error?
Haskell has the type constructor Maybe
, perfectly suited for this kind of results.
Despite that, I've seen Haskell programmers prefer a different approach: when they aren't sure the function will return any result, they declare its return type as a list.
When the list contains something, it is the result of the computation.
When the list is empty, it is no surprise to any user of the function - since it's natural for lists to be empty sometimes.
This way in Python there would be no need to worry about None
as a result either.
From the Haskell manual on monads (turns out the List
type is a monad too):
One use of functions which return lists is to represent ambiguous computations — that is computations which may have 0, 1, or more allowed outcomes.
In a computation composed from ambigous subcomputations, the ambiguity may compound, or it may eventually resolve into a single allowed outcome or no allowed outcome at all. During this process, the set of possible computational states is represented as a list.
The List monad thus embodies a strategy for performing simultaneous computations along all allowed paths of an ambiguous computation [^1].
‒ https://wiki.haskell.org/All_About_Monads#List_is_also_a_monad
If you've read about Quantum Electrodynamics, the statement [^1] may sound familiar. From Feynman's Lectures on Physics:
The first way of thinking that made the law about the behavior of light evident was discovered by Fermat in about 1650, and it is called the principle of least time, or Fermat’s principle.
His idea is this: that out of all possible paths that it might take to get from one point to another, light takes the path which requires the shortest time.
‒ https://www.feynmanlectures.caltech.edu/I_26.html
In some experiments, Feynman indicated at another time, the results seem exactly as if light really did travel all the paths it could possibly take, and only then took the path we are able to observe in the experiment.