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

Stefan Holdermans sholderm at students.cs.uu.nl
Wed Mar 24 16:38:43 EST 2004


Alex,

AG> I am new to haskell and would look to write a function 
AG> equivalent to the following loop in C

AG> int value = 500000;
AG> int part_stack[4];
AG> int *part_ptr = part_stack;
AG> for (; value; value /= 10000)
AG>       *part_ptr++ = value % 10000;

What about this?

> part     :: Int -> Int -> [Int]
> part k n =  unfoldr f k
>   where f 0 = Nothing
>         f m = Just (m `mod`n, m `div` n)

part 500000 10000, for instance, produces the [0, 50].

Here, unfoldr is the dual of the function foldr from the Prelude.

> unfoldr     :: (b -> Maybe (a,b)) -> b -> [a]
> unfoldr f b = case (f b) of
>                 Nothing    -> []
>                 Just (a,b) -> a : unfoldr f b

HTH,

Stefan




More information about the Haskell-Cafe mailing list