User-Defined Types

Nick Grey nickgrey0112@farrand.net
Wed, 1 May 2002 16:24:43 +0100


On Wednesday 01 May 2002 15:52, Matthias wrote:

> where (Tree a) is obviously the data-constructor out of "the other
> namespace". I guess that the () is warping Tree a from the
> "data-constructor-namespace" into the "type-constructor-namespace".

You are misunderstanding slightly.  The quote you mention is reffering to the 
fact that the names of types and the names of constructors are in different 
namespaces.  So for example, the following is legal:

> type Foo = Int
> data Bar = Foo

Note that the Foo in the second declaration has nothing to do with the Foo in 
the first declaration.  If types and constructors were in the same namespace, 
this would be illegal, because there Foo in the second declaration would be 
interpretted as a type.

> Also i would not regret some hints about "->" which
> is used in function-type-definitions. I would prefer writing
> 	plus :: a,a -> a

Imagine you have two functions for adding:

> plus1 :: Int -> Int -> Int
> plus1 x y = x + y

> plus2 :: (Int, Int) -> Int
> plus2 (x, y) = x + y

plus1 and plus2 do much the same thing.  But there is a slight difference.

If I give plus2 a pair of ints it returns another int.  We know this because 
of the type.  (Int, Int) -> Int means "Give me something of type (Int, Int) 
and I will give you an Int".

Now look at the type for plus1.  Because -> associates to the right, this type 
is interpretted as Int -> (Int -> Int).  What does this type mean?  It means 
"Give me something of type Int and I will give you something of type Int -> 
Int".  So if you give plus1 a single int, it will give you another function!  
What does this function do?  If you gave plus1 a 7, the function returned by 
plus1 is a function that takes an int and adds 7 to it.

This is why it's better to use Int -> Int -> Int than it is to use (Int, Int) 
-> Int.  For example, if I want a function that adds 1 to a number, I can 
write:

incr = plus1 1

This is called partial application.

But I can't do the same with plus2.  plus2 expects something of type (Int, 
Int), and there is no way to give it half a pair.

> What is meant that -> is "associating to the right"?

It basically means "when there is some doubt about order, pretend there are 
brackets on the right".  If an operator (eg #) is used like this:

x # y # z

If # associates to the right then above expression means:

x # (y # z)

If # associates to the left then it means:

(x # y) # z

> Is there a name for '->'?

Don't know about anyone else, but I pronounce it "to".  So plus1 has type "Int 
to Int to Int".  plus2 has type "Pair of Ints to Int".

Regards,
Nick