What does the : infix operator do in Haskell?

后端 未结 4 1785
甜味超标
甜味超标 2020-12-03 00:45

I\'m reading A Gentle Introduction to Haskell (which is not so gentle) and it repeatedly uses the : operator without directly explaining what it does.

S

4条回答
  •  遥遥无期
    2020-12-03 01:23

    It is the type constructor for lists. It is no different from any other type constructor like Just or Left, except that it is infix. Valid type constructors can either be words starting with a capital letter, or symbols starting with a colon.

    So you can define infix constructors for your own data types. For example:

    data MyList a = a :> MyList a
                  | Empty
    

    in the above code we define a type called MyList with two constructors: the first is a weird-looking constructor :> which takes an element and another MyList a; the second is an empty constructor Empty which is equivalent to [] in Haskell's native lists.

    The above is equivalent to :

    data MyList a = Cons a  (MyList a)
                  | Empty
    

提交回复
热议问题