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.
In computer programming, cons (/ˈkɒnz/ or /ˈkɒns/) is a fundamental function in most dialects of the Lisp programming language. cons constructs memory objects which hold two values or pointers to two values. These objects are referred to as (cons) cells, conses, non-atomic s-expressions ("NATSes"), or (cons) pairs.
(->) is often called the "function arrow" or "function type constructor", and while it does have some special syntax, there's not that much special about it. It's essentially an infix type operator. Give it two types, and it gives you the type of functions between those types.
The ++ operator is the list concatenation operator which takes two lists as operands and "combines" them into a single list.
If you need to figure out what the type of an object is in a Haskell program, I hope this is helpful. Note that if you are in GHCI, you can just put :type before your expression to determine the expression's type, or use :set +t to see the type of every expression in GHCI.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With