Can anyone explain (better with an example in plain English) what a list monad can do to model non-deterministic calculations? Namely what the problem is and what solution a
The list monad can be though of representing "all possible results from a non-deterministic computation". For example, the function
f x = [x, x + 1, x + 2]
can be interpreted as a non-deterministic computation that takes x
and returns one of x
, x+1
and x+2
.
The function
g x = [2 * x, 3 * x]
can be interpreted as a non-deterministic computation that takes x
and returns either 2 * x
or 3 * x
. The "composition" of these two non-deterministic computations should be another non-deterministic computation which takes x
, transforms it to one of x
, x + 1
or x + 2
, and then then either doubles it or triples it. Thus in terms of lists the result should be a list of all six possibilities
Now
g =<< f x = [2 * x, 3 * x, 2 * (x + 1), 3 * (x + 1), 2 * (x + 2), 3 * (x + 2)]
so indeed this models non-determinism as we expected.
(There is some awkwardness to using lists for non-determinism, since they also have a ordering of elements. A "set monad" would probably be a more natural way to model non-determinism. Lists certainly contain enough information to model non-determinism, but the ordering means that we have more information than necessary.)
EDIT: in fact what I wrote only really goes as far as using the list applicative instance. To get something that fully takes advantage of the monadic interface you want a computation that returns a number of results that depends on its input, for example
g 0 = [1000, 1001]
g x = [2 * x, 3 * x, 4 * x]
although admittedly this is a completely arbitrary and unmotivated example!