Using monads for trivial tasks like list manipulation?

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

    Here is a very stupid way to find pairs of divisors for a given integer:

    divisors:: Int -> [(Int,Int)]
    divisors n = do
      x <- [1 .. n]
      y <- [1 .. n]
      if x*y == n then return (x, y) else []
    

    The meaning of this fragment ought to be fairly straight-forward. Obviously, this is a stupid way to solve this specific problem. (There are far more efficient methods possible in this case.) But now imagine some more complicated problem, where this search is very complex. This kind of idiom for searching can be quite useful.

提交回复
热议问题