Whenever I read about Monad example, they always present IO as a case study.
Are there any examples of monads doing list manipulation which somebody could present? I apr
A classic example of using the list monad to cleverly write a "simple" list utility function is this:
import Control.Monad (filterM)
-- | Compute all subsets of the elements of a list.
powerSet :: [a] -> [[a]]
powerSet = filterM (\x -> [True, False])
The type of filterM
is Monad m => (a -> m Bool) -> [a] -> m [a]
. In the context of the list monad, this is a nondeterministic list filter: a filter operation that takes a nondeterministic predicate that returns a list of alternative answers. The result of filterM
is in turn a list of alternative possible results.
Or in simpler language, filterM (\x -> [True, False])
means: for each element of the list, I want both to keep it and throw it away. filterM
figures out all possible combinations of doing this for each list element.