[Haskell-beginners] Haskell Generic Function Question

Jan Jakubuv jj36 at hw.ac.uk
Thu May 28 13:01:58 EDT 2009


Hi Bryan,

I think that it isn't a very good idea to use `read/show` to do some numeric
computations. You can use standard functions `div` and `mod` which work with
any Integrals.

    digits :: (Integral a) => a -> [a]
    digits 0 = []
    digits n = digits (n `div` 10) ++ [n `mod` 10]

This code behaves differently on 0 then your one (also on negative numbers).
You can fix it easily, and moreover, you may want to use `divMod` and some
accumulator to improve efficiency:

    digits2 :: (Integral a) => a -> [a]
    digits2 0 = [0]
    digits2 n = digits2' n [] where
        digits2' 0 acc = acc
        digits2' n acc = let (r,d) = divMod n 10 in digits2' r (d:acc)

I hope I understood well what you were asking about ;-)

Btw, to make your code working I needed to write it as:

    toIntegralList :: (Read a, Integral a) => a -> [a]
    toIntegralList (x :: a)  = map (\c -> read [c] :: a) (show x)

Sincerely,
  Jan.

On Thu, May 28, 2009 at 11:50:36AM -0400, William Gilbert 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.
> 
> Thanks In Advance,
> Bryan
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners


-- 
Heriot-Watt University is a Scottish charity
registered under charity number SC000278.



More information about the Beginners mailing list