Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "chain" monad function in Haskell?

Tags:

haskell

monads

Explain about a "duplicate"

Someone point to Is this a case for foldM? as a possible duplicate. Now, I have a strong opinion that, two questions that can be answered with identical answers are not necessarily duplicates! "What is 1 - 2" and "What is i^2" both yields "-1", but no, they are not duplicate questions. My question (which is already answered, kind of) was about "whether the function iterateM exists in Haskell standard library", not "How to implement a chained monad action".

The question

When I write some projects, I found myself writing this combinator:

repeatM :: Monad m => Int -> (a -> m a) -> a -> m a
repeatM 0 _ a = return a
repeatM n f a = (repeatM (n-1) f) =<< f a

It just performs a monadic action n times, feeding the previous result into the next action. I tried some hoogle search and some Google search, and did not find anything that comes with the "standard" Haskell. Is there such a formal function that is predefined?

like image 492
Carl Dong Avatar asked Oct 20 '15 03:10

Carl Dong


1 Answers

You can use foldM, e.g.:

import Control.Monad

f a = do print a; return (a+2)

repeatM n f a0 = foldM (\a _ -> f a) a0 [1..n]

test = repeatM 5 f 3
  -- output: 3 5 7 9 11
like image 93
ErikR Avatar answered Sep 27 '22 21:09

ErikR