【问题标题】:Is the cons operation cons elements from right to left?cons操作是cons元素从右到左吗?
【发布时间】:2018-11-29 03:25:06
【问题描述】:

我们知道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]

我知道这可能不是一个合适的例子,因为: 操作包含一个元素和一个列表。但我只是想知道它在1:2:[] 中是如何工作的

【问题讨论】:

  • (:) 必须是右关联的,因为如果 1:2:[] 被解析为 (1:2):[] 会产生类型错误。

标签: haskell operator-precedence syntactic-sugar cons


【解决方案1】:

错误信息可能会更好。但是1 : 2 不会创建列表。你需要:

1 : [2]

[2]2:[] 的语法糖。

所以现在你可以推断1:2:[] 扩展为1 : (2 : [])。您还可以通过在ghci 中使用:info 命令来发现此行为:

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

它说(:) 运算符是右结合的。

此外,还有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]

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 2013-05-12
    • 2010-11-21
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多