Why can't constructors without variables of type WITHOUT without parameters?

As a newbie, I don’t understand why this is not allowed:

data Pair = Pair ab 

That is, why Pair 5 "foo" and Pair 'C' [] HAVE produce different types? Why are they not allowed to create values ​​of type Pair ?

I study "Learn you a", RWH, and the Haskell WikiBook, but could not find an exact, awkward language describing the parameterized types I'm looking for.

+4
source share
2 answers

In fact, the problem is that you will not have information about the contents of Pair . If all you know is that it contains a value of any type, the only real function that you could use on it would be id , which is pretty useless!

The problem is that since each value can be anything, you have no guarantee whatsoever about them. So you couldn't even use == : what if the value was a function? You cannot compare functions for equality!

Imagine you are writing a function that acts on your hypothetical Pair type:

 fn (Pair ab) = ... 

What other functions could you use on a and b ?

Anything of any particular type (for example, Int -> Int or something else) will not work, because you cannot determine if a Int . More complex types, such as Num n => n -> n , will not work because you do not even know if a is a number. The only functions that will work are those that have types like t1 -> t1 or t1 -> t2 . However, the only reasonable function of the first type is id and there is generally no reasonable function of the second type.

Now you can simply say: "I'm going to try this function, if the type does not work, throw an error." But then it will be dynamic typing and basically will completely discard the type system. It sounds awful, but sometimes it can make sense, so you can use Data.Dynamic to achieve something similar. However, you should not worry about this as a beginner or a chance, you will never need to use it - not yet. I just turn it on for the sake of completeness.

+10
source

With the extension of the language of existential types, you can define this type:

 {-# LANGUAGE ExistentialQuantification #-} data Pair = forall a b. Pair ab a, b :: Pair a = Pair 1 2 b = Pair "abc" 'x' 

Here both a and b are of the same type.

Usually this is not done because for something useful with Pair you need to know what it contains, and the definition of Pair removes all this information.

That way, you can create such values ​​if you want, but it's hard to find something useful for them.

+4
source

Source: https://habr.com/ru/post/1414262/


All Articles