use*_*628 3 haskell syntactic-sugar operator-precedence cons
我们知道1:2:[]会回来[1,2].
我刚试过1:2,这给了我一个错误.
<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]
Run Code Online (Sandbox Code Playgroud)
我知道这可能不是一个恰当的例子,因为:操作包含元素和列表.但我只是想知道它是如何运作的1:2:[]
错误消息可能更好.但1 : 2不会创建列表.你需要:
1 : [2]
Run Code Online (Sandbox Code Playgroud)
并且[2]是一种语法糖2:[].
所以现在你可以推断出1:2:[]扩展到了1 : (2 : []).您还可以使用以下:info命令发现此行为ghci:
Prelude> :info (:)
data [] a = ... | a : [a] -- Defined in ‘GHC.Types’
infixr 5 :
Run Code Online (Sandbox Code Playgroud)
它说(:)运营商是正确的联想.
此外,还有一些TemplateHaskell技巧可以让您了解如何在结果表达式中指定括号:
$ 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]
Run Code Online (Sandbox Code Playgroud)