[Haskell-beginners] Haskell Generic Function Question

Paul Visschers mail at paulvisschers.net
Thu May 28 12:49:15 EDT 2009


I assume the problem is that the function doesn't compile. This should work:
> toIntegralList :: (Read a, Show a) => a -> [a]
> toIntegralList x = map (\c -> read [c]) (show x)
This adds the required Read and Show instances, which are necessary
because of the read and show functions, respectively. Also note that I
have omitted your extra type annotation, which also causes an compile error.

The problem with this functions is that you can use it on a lot of stuff
that isn't a number, and you'll get a runtime read error, to remedy
this, just reinsert the Integral type class requirement:
> toIntegralList :: (Integral a, Read a, Show a) => a -> [a]
> toIntegralList x = map (\c -> read [c]) (show x)

Hope this helps,
Paul

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


More information about the Beginners mailing list