As a beginner, it's not obvious to me why this is not allowed:
data Pair = Pair a b
That is, why do Pair 5 "foo"
and Pair 'C' []
HAVE to produce different types? Why is it not allowed for them both to create values of type Pair
?
I'm learning from "Learn you a", RWH, and the Haskell WikiBook, but have not been able to find the kind of precise, wonky language describing parametrized types that I'm looking for.
Fundamentally, the issue is that you would have no information about the contents of Pair
. If all you know is that it contains a value of any type, the only real function you could use on it would be id
, which is pretty useless!
The problem is that, since each value could be anything, you have no guarantees about them at all. So you couldn't even use ==
: what if the value was a function? You can't compare functions for equality!
Imagine writing a function acting on your hypothetical Pair
type:
fn (Pair a b) = ...
What other functions could you use on a
and b
?
Anything with any sort of concrete type (e.g. Int -> Int
or something) wouldn't work because you can't tell if a
is an Int
. More complicated types like Num n => n -> n
wouldn't work because you don't even know if a
is a number. The only functions that would work are ones with types like t1 -> t1
or t1 -> t2
. However, the only reasonable function of the first type is id
and there is no reasonable function of the second type at all.
Now, you could just say "I'm going to try this function, if the type doesn't work, throw an error." But this would then be dynamic typing and would basically be throwing away the type system entirely. This sounds horrible, but it might make sense sometimes, so you can use Data.Dynamic
to accomplish something like that. However, you shouldn't worry about it as a beginner and chance are you will never need to use it--I haven't, so far. I'm just including it for the sake of completeness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With