Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't value constructors take type variables WITHOUT parameterizing the type?

Tags:

haskell

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.

like image 835
spartan_dev Avatar asked Dec 10 '22 00:12

spartan_dev


1 Answers

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.

like image 61
Tikhon Jelvis Avatar answered Apr 09 '23 02:04

Tikhon Jelvis