[Haskell-beginners] Re: Haskell Generic Function Question

Ertugrul Soeylemez es at ertes.de
Thu May 28 12:55:06 EDT 2009


William Gilbert <gilbertw1 at gmail.com> wrote:

> I am trying to write a function that will covert either an integer or
> an int into a list containing its digits.
>
> ex. toIntegralList 123 -> [1,2,3]
>
> I have written the following definition that tries to use read to
> generically cast a string value to an Integral type that is the same
> as the Integral passed in:
>
> toIntegralList :: (Integral a) => a -> [a]
> toIntegralList x = map (\c -> read [c] :: a) (show x)
>
> I understand it would be very simple to just create two functions, one
> that converts an Int and one that converts an Integer, however I was
> wondering if there were any way to accomplish what I am trying to do
> here.

Of course you can use read and show for that, but personally I find it
more appropriate to write the algorithm yourself.  It will be faster and
give you a much more useful digit ordering, namely starting with the
least significant digit:

  toDigits :: Integral i => i -> i -> [i]
  toDigits base = takeWhile (>0) . map (`rem` base) . iterate (`div` base)

  toDecimalDigits :: Integral i => i -> [i]
  toDecimalDigits = toDigits 10

  fromDigits :: Num a => a -> [a] -> a
  fromDigits base = foldr (\d c -> base*c + d) 0

  fromDecimalDigits :: Num a => [a] -> a
  fromDecimalDigits = fromDigits 10


Greets,
Ertugrul.


-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://blog.ertes.de/




More information about the Beginners mailing list