简体   繁体   中英

What does Cons and :-: mean in Haskell?

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 pqr 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.

 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.

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 . Ie instead of Cons 1 someList one can write 1 :-: someList .

:-: 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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM