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?
First, you have an error in your code. Data types must start with capital letters:
(Note that
Stringis 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: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:
We could have included a constraint in the data type, like this:
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.”