Using monads for trivial tasks like list manipulation?

前端 未结 6 1400
栀梦
栀梦 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:00

    Another example is constructing all the divisors of a number from its prime factorization (though out of order):

    divs n = map product 
               . mapM (\(p,n)-> map (p^) [0..n]) 
               . primeFactorization $ n
    
    -- mapM f = sequence . map f
    
    -- primeFactorization 12  ==>  [(2,2),(3,1)]  -- 12 == 2^2 * 3^1
    

    The function f in mapM f == sequence . map f produces a list of powers of a factor, for each entry in the input list; then sequence forms all paths through the lists picking one number from each at a time; then this list of all possible combinations is fed to map product which calculates the divisors:

    12                                      -- primeFactorization:
    [(2,2),(3,1)]                           -- map (\(p,n)-> ...):
    [ [1,2,4], [1,3] ]                      -- sequence:
    [[1,1],[1,3],[2,1],[2,3],[4,1],[4,3]]   -- map product:
    [1,3,2,6,4,12]                          --   the divisors of 12
    

    The great description given in Luis Casillas's answer applies here too:

    In the context of the list monad, mapM :: (Monad m) => (a -> m b) -> [a] -> m [b] is a nondeterministic list map: a mapping operation that maps a nondeterministic function - such that produces a list of alternative results - over a list, creating all the alternative possible lists of results.

提交回复
热议问题