What does the : infix operator do in Haskell?

后端 未结 4 1783
甜味超标
甜味超标 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:20

    The : operator in Haskell is the constructor for lists. It 'cons' whatever is before the colon onto the list specified after it.

    For instance, a list of integers is made by 'consing' each number onto the empty list, e.g;

    The list [1,2,3,4] can be constructed as follows:

    • 4 : [] (consing 4 to the empty list)
    • 3 : [4] (consing 3 onto the list containing 4)
    • 2 : [3,4] (consing 2 onto the list containing 3, 4)
    • 1 : [2,3,4] (consing 1 onto the list containing 2,3,4)

    giving you;

    [1,2,3,4]
    

    Written fully that's;

    1 : 2 : 3 : 4 : []
    

提交回复
热议问题