[Haskell-cafe] Monads as control structures?
ChrisK
chrisk at MIT.EDU
Thu Oct 27 12:09:17 EDT 2005
Try this:
This line is before the loop
sequence_ $ replicate 10 $ do
line 1
line 2
...
last line
This line is after the loop
Now you can use shorthand via
loopN n block = sequence_ $ replicate n block
So that you can write:
This line is before the loop
loopN 10 $ do
line 1
line 2
...
last line
This line is after the loop
If you need a loop parameter "mapM/mapM_ block [1...10]" works well.
Creighton Hogg wrote:
> Hi,
> so I'm a newbie getting used to Haskell. I'm writing some
> simple things like genetic algorithms in it for practice,
> and I keep coming across something that really bugs me:
> are there any standard libraries that allow you to
> do imperative style for or while loops using monads to keep
> track of state?
>
> I know there's things like "until", but honestly that's not
> quite what I'm looking for.
>
> I just think there should be a simple way to say "execute
> this block of code 10 times" without having to wrap it up in
> recursion.
>
> Haskell seems to me to be a very powerful language, and it
> looks like it should be possible to define control
> structures such as for loops using monads.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
More information about the Haskell-Cafe
mailing list