Reputation: 331
In LYAHFGG, one chapter says that list is defined as:
data List a = Cons a (List a) deriving (Show, Read, Eq, Ord)
I understand what most of this means apart from Cons. When I try :t Cons
and :i Cons
in ghci
I get a not in scope error. Later on in the chapter it also talks about :-: and how it's the same as Cons
infixr 5 :-:
data List a = Empty | a :-: (List a) deriving (Show, Read, Eq, Ord)
But again I really don't understand what this :-:
means either.
In another resource, in a section about data types, they define the following data type:
data Expr = X
| Const Int
| Expr :+: Expr
| Expr :-: Expr
| Expr :*: Expr
| Expr :/: Expr
| IfZero Expr Expr Expr
deriving (Eq, Ord)
Where IfZero p q r
is the same as if p == 0 then q else r
. Is this the same thing? I'm mostly confused as to what the two :
s mean, and if it's mandatory syntax or just style choice.
Upvotes: 11
Views: 26570
Reputation: 19772
:-:
is just an infix name for a data constructor. You could see that data
declaration as equivalent to
data List a = Empty | (:-:) a (List a)
Semantically, there is no difference between using (:-:)
or Cons
, but it's much nicer to read
1 :-: 2 :-: 3 :-: 4 :-: Empty
than either
Cons 1 (Cons 2 (Cons 3 (Cons 4 Empty)))
or
1 `Cons` (2 `Cons` (3 `Cons` (4 `Cons` Empty)))
Upvotes: 8
Reputation: 116174
data List a = Cons a (List a) deriving (Show, Read, Eq, Ord)
I understand what most of this means apart from Cons. When I try
:t Cons
and:i Cons
inghci
I get a not in scope error.
You need to load the Haskell source file with the data
declaration before you can have Cons
in scope. Or, alternatively, you can enter that data
line directly in GHCi.
For serious code, it's easier if you put it in a file and load it. This is because the learning process typically involves modifying the file a bit, reloading it, trying some test in GHCi, modifying the file again, etc. Doing this in GHCi is cumbersome.
Anyway, Cons
is just the constructor name -- it is an arbitrary name. You can use data List a = Foobar a (List a) ....
and name it Foobar
, if you wish. Cons
is a historic name, though, originating from Lisp.
:-:
is another arbitrary name for the constructor, except that it can be used infix. I.e. instead of Cons 1 someList
one can write 1 :-: someList
.
Upvotes: 16