3

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:[]

Shersh
  • 9,019
  • 3
  • 33
  • 61
user8314628
  • 1,952
  • 2
  • 22
  • 46
  • 5
    `(:)` **must** be right-associative because if `1:2:[]` was parsed as `(1:2):[]` it would create a type error. – 4castle Jun 20 '18 at 05:40

1 Answers1

6

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]
Shersh
  • 9,019
  • 3
  • 33
  • 61