[Haskell-cafe] how to write a loop in haskell way
lemming at henning-thielemann.de
Sun Dec 19 11:41:09 CET 2010
On Sun, 19 Dec 2010, ender wrote:
>> 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)
> 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.
More information about the Haskell-Cafe