Search code examples
haskelloperator-precedencesyntactic-sugarcons

Is the cons operation cons elements from right to left?


We know 1:2:[] will returns [1,2].

I just tried 1:2, this gives me an error.

<interactive>:48:1: error:
    ? Non type-variable argument in the constraint: Num [a]
      (Use FlexibleContexts to permit this)
    ? When checking the inferred type
        it :: forall a. (Num a, Num [a]) => [a]

I know this may be not a proper example since the : operation cons an element and a list. But I'm just wondering how it works in 1:2:[]


Solution

  • Error message could be better. But 1 : 2 won't create list. You need:

    1 : [2]
    

    And [2] is a syntax sugar for 2:[].

    So now you could deduce that 1:2:[] is expanded into 1 : (2 : []). You can also discover this behavior by using :info command in ghci:

    Prelude> :info (:)
    data [] a = ... | a : [a]   -- Defined in ‘GHC.Types’
    infixr 5 :
    

    It says that (:) operator is right associative.

    Also, there exist TemplateHaskell trick which allows you to see how parenthesis will be specified in resulting expression:

    $ ghci -ddump-splices -XTemplateHaskell
    Prelude> $([| 1:2:[] |])  -- put expression with bunch of operators here
    <interactive>:1:3-14: Splicing expression
        [| 1 : 2 : [] |] ======> (1 GHC.Types.: (2 GHC.Types.: []))
    [1,2]