Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do the same thing n times in Haskell

Tags:

haskell

Excuse me if this is a really dumb question, but I've read through one book and most of another book on Haskell already and don't seem to remember anywhere this was brought up.

How do I do the same thing n times? If you want to know exactly what I am doing, I'm trying to do some of the Google Code Jam questions to learn Haskell, and the first line of the input gives you the number of test cases. That being the case, I need to do the same thing n times where n is the number of test cases.

The only way I can think of to do this so far is to write a recursive function like this:

recFun :: Int -> IO () -> IO ()
recFun 0 f = do return ()
recFun n f = do
    f
    recFun (n-1) f
    return ()

Is there no built in function that already does this?

like image 973
Richard Fung Avatar asked May 10 '15 17:05

Richard Fung


1 Answers

forM_ from Control.Monad is one way.

Example:

import Control.Monad (forM_) 

main = forM_ [1..10] $ \_ -> do
    print "We'll do this 10 times!"

See the documentation here

http://hackage.haskell.org/package/base-4.8.0.0/docs/Control-Monad.html#v:forM-95-

like image 183
Sheev Avatar answered Oct 05 '22 10:10

Sheev