Data types basics
Hal Daume III
hdaume at ISI.EDU
Tue Nov 4 22:10:03 EST 2003
Hi again,
On Wed, 5 Nov 2003, Patty Fong wrote:
> Hi to anyone reading this. i'm still strugling a bit with data type
> declarations.
>
> The was i understand it is that if i delcare a new data type:
>
> data myType = myType a | b | c
This isn't entirely correct. The names of types have to begin with
capital letters, as do constructors (more later). So you would need this
to be:
data MyType = MyType A | B | C
where A is an existing type.
This type now has three constructors:
MyType :: A -> MyType
B :: MyType
C :: MyType
It's perhaps a bit easier to understand when the names are different.
When we say:
data Foo = Bar Int | Baz String
this means that a "Foo" is of one of two forms (the "|" can be read as
disjunction). A value of type Foo is either of the form "Bar x" for some
x which is an Int or "Baz y" for some y which is a String.
"Bar" and "Baz" are called "constructors" because they take arguments and
"construct" a Foo. So, in this case,
Bar :: Int -> Foo
Baz :: String -> Foo
are the two constructors.
Of course, you have have any number of constructors and each can have any
number of arguments.
data Foo = Bar | Baz Int | Bazaa String Bool
Now there are three constructors:
Bar :: Foo
Baz :: Int -> Foo
Bazaa :: String -> Bool -> Foo
they can be recursive:
data Foo = Bar | Baz Int Foo
Bar :: Foo
Baz :: Int -> Foo -> Foo
and can have "type variables", for instance:
data Foo a = Bar | Baz a
here, something of type "Foo a" is either of the form Bar or of the form
Baz x for some x which is of type a. This has constructors:
Bar :: Foo a
Baz :: a -> Foo a
I hope this sheds some light on the issue...
--
Hal Daume III | hdaume at isi.edu
"Arrest this man, he talks in maths." | www.isi.edu/~hdaume
More information about the Haskell-Cafe
mailing list