Using monads for trivial tasks like list manipulation?

前端 未结 6 1402
栀梦
栀梦 2021-02-09 05:13

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

6条回答
  •  不知归路
    2021-02-09 06:10

    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.

提交回复
热议问题