[Haskell-cafe] Function to cast types

Roel van Dijk vandijk.roel at gmail.com
Sun Mar 22 09:53:15 EDT 2009


> I'm new to haskell, I'm wondering how can you write a function that will do
> the following:
>
> fromIntToString :: Int -> String
>
> this is a cast function to cast an Int to a String.

I'll assume that by a cast you mean a conversion from one type to
another where no information is lost.

-- Let's assume that we can represent every Int using a String
intToString :: Int -> String
intToString n = ...

-- Not every member of String can be interpreted as an Int, for
-- example "aabc" is nonsense when viewed as an Int.
stringToInt :: String -> Maybe Int
stringToInt s = ...

-- This property should hold for every Int. It states that given some
-- Int called n we can convert it to a string and back without losing
-- information.
prop_intString :: Int -> Bool
prop_intString n = maybe False (== n) . stringToInt . intToString $ n

Using such a property can be really useful to test your implementation
of intToString and stringToInt.

> I know such function
> exist, however let's assume it didn't exist. How would I write such
> function? Cause I have no idea, because there are infinity possibilities if
> I do it like:
>
> fromIntToString x | x == 1 = "1"
>                          | x == 2 = "2"
> -- And so on...
It might be useful to first write this function first:

intToDigits :: Int -> [Int]
intToDigits n = ...

It should convert an integer to a list of its digits (using normal base 10):

intToDigits 123 == [1, 2, 3]

Then you can write a function which takes such a list and converts it
to a string. (Hint: use 'map' in combination with a function of type
'Int -> Char')

You have to take extra care if you also want to support negative numbers.

> I've also thinked about defining the defining the data types Int and String
> (I know you cannot redefine them, at least I think so), however I've no
> succes.
You can create your own datatypes which behave roughly the same as Int
and String. You will never be able to create something which behaves
exactly as a String because it is treated a bit special (it has its
own syntax).

import Data.String

data MyInt = ...
data MyString = ...

instance Num MyInt where ...
instance IsString MyString where ...

By creating an instance of Num for your own type MyInt you'll be able
to use the familiar operators +, - etc... If you want all the
functionality that normal Ints have for your own type you'll also need
instances of Bounded, Enum, Eq, Integral, Num, Ord, Read, Real, Show
and Ix. I might have forgotten a few :-) Some of those can be
automatically derived for you. (data MyInt = ... deriving Show, for
example)

I hope some of this is useful to you.


More information about the Haskell-Cafe mailing list