[Haskell-cafe] how to write a loop in haskell way

Lennart Augustsson lennart at augustsson.net
Sun Dec 19 11:58:51 CET 2010


Recursion replaces loops.  If it needs to be monadic or not depends on what
you want to do.

On Sun, Dec 19, 2010 at 10:53 AM, ender <crazyender at gmail.com> wrote:

> 2010/12/19 Henning Thielemann <lemming at henning-thielemann.de>:
> >
> > On Sun, 19 Dec 2010, ender wrote:
> >
> >>>  do
> >>>  alloca $ \value -> do
> >>>  poke value (500000::Int)
> >>>  allocaArray 4 $ \part_stack -> do
> >>>  alloca $ \part_ptr -> do
> >>>  poke part_ptr part_stack
> >>>  let loop = do
> >>>           val <- peek value
> >>>           if val == 0 then return () else do
> >>>           p <- peek part_ptr
> >>>           poke p (val `rem` 10000)
> >>>           poke part_ptr (p `plusPtr` 1)
> >>>           poke value (val `quot` 10000)
> >>>           loop
> >>>  loop
> >>
> >> and I really think that's not a "haskell way", it's just translate c
> >> code into haskell code byte by byte
> >> My question is: how to translate above c code into haskell in "haskell
> >> way"
> >
> > If the count of loop runs does not depend on results of the loop body,
> then
> > 'mapM' and 'mapM_' applied to the list of increasing pointers are your
> > friends. In your case, the loop aborts when 'val' becomes zero. I'm
> > certainly thinking too complicated, but you might use MaybeT IO () (e.g.
> > from transformers package) and abort 'mapM_' with 'mzero' when 'val'
> becomes
> > zero. (MaybeT IO a) is like an IO monad with an early exit (somehow an
> > exception) option.
> >
> Hi Henning:
>   Thanks for your quick reply. So recursive and monad is the proper
> way to simulate loop,right?
>
> Thanks and BR
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20101219/6adb1519/attachment.htm>


More information about the Haskell-Cafe mailing list