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

Robin Green greenrd at greenrd.org
Mon Jan 12 16:48:08 EST 2009


On Mon, 12 Jan 2009 21:04:35 +0100 (CET)
Henning Thielemann <lemming at henning-thielemann.de> wrote:

> 
> On Mon, 12 Jan 2009, Andrew Coppin wrote:
> 
> > 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)
> 
> I have the nice function 'toMaybe' which simplifies this to:
>    unfoldr (\n -> toMaybe (n>0) (n `mod` b, n `div` b))

I would use the more general idiom:

     unfoldr (\n -> guard (n > 0) >> return (n `mod` b, n `div` b))

-- 
Robin


More information about the Haskell-Cafe mailing list