Search code examples
haskelltyping

Haskell typing for Int's and Double's


Just quick question about typing.

If I type into ghci :t [("a",3)] I get back [("a",3)] :: Num t => [([Char], t)]

Inside a file I have defined a type as:

type list = [(String, Int)]

How can I change the type to support both Ints and Doubles with the type I have defined, similar to what I wrote in ghci?


Solution

  • First, you have an error in your code. Data types must start with capital letters:

    type List = [(String, Int)]
    

    (Note that String is a type synonym for [Char], i.e. they are exactly the same type). We'll solve your problem in a roundabout way. Note that you can make the type completely general in the second slot of the tuple:

    type List a = [(String,a)]
    

    so that your type parameterizes over arbitrary types. If you need to specialize to numeric types in some function, then you can make that specialization for each function individually. For example:

    foo :: Num a => List a
    foo = [("Hello",1),("World",2)]
    

    We could have included a constraint in the data type, like this:

    data Num a => List a = List [(String,a)]
    

    but you would still have to include the constraint Num a => ... in every function declaration, so you don't actually save any typing. For this reason, Haskell programmers generally follow the rule "Don't include type constraints in data declarations."