[Haskell-cafe] unfoldr [ANN: HLint 1.2]

Andrew Coppin andrewcoppin at btinternet.com
Mon Jan 12 14:56:03 EST 2009

Neil Mitchell wrote:
> Hi Andrew,
>>> HLint will automatically detect if you should have used a map, a foldr
>>> or a foldl and suggest how to change your code. In the GHC, darcs and
>>> Hoogle code bases there are no obvious map-like functions, which is a
>>> good sign :-)
>> ...What an intriguing idea. Clearly I'm going to have to play with this
>> sometime soon.
>> Does it suggest unfoldr too?
> No, but it could do in the future - I never use unfold's in my code,
> so am not really familiar with them. But I will look into them, do you
> have any examples where it should suggest unfoldr so I can play with
> them?

Off the top of my head, try this:

  convert b 0 = []
  convert b n = n `mod` b : convert b (n `div` b)

(Takes a number and yields the radix-B representation of it. Backwards.)

  convert b = unfoldr (\n -> if n > 0 then Just (n `mod` b, n `div` b) 
else Nothing)

It's also useful for converting a data structure into a list:

  heap_to_list = unfoldr (\h -> if heap_empty h then Nothing else Just 
(heap_top h, heap_delete_top h))

Those are the major uses I'm aware of. I'm sure somebody else will think 
of others. (IIRC, unstream is implemented as an unfold...?)

More information about the Haskell-Cafe mailing list