[Haskell-cafe] loop in C , recursion in haskell

Simon Marlow simonmar at microsoft.com
Wed Mar 24 15:51:54 EST 2004


 
> On Thu, Mar 25, 2004 at 01:38:44AM +1100, Alex Gontcharov wrote:
> > Hi,
> > 
> > I am new to haskell and would look to write a function equivalent
> > to the following loop in C
> > 
> > int value = 500000;
> > int part_stack[4];
> > int *part_ptr = part_stack;
> > for (; value; value /= 10000)
> >       *part_ptr++ = value % 10000;
> 
> part_stack :: [Int]
> part_stack = [0,50]
> 
> Note that I've performed a memoization optimization--this 
> makes the code both smaller, faster and easier to read! :P

Ignore David, he's pulling your leg.  Here's the proper translation:

 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

Cheers,
	Simon


More information about the Haskell-Cafe mailing list