【问题标题】:Non type-variable argument in the constraint error, while using with infix约束错误中的非类型变量参数,同时与中缀一起使用
【发布时间】:2022-01-15 19:36:56
【问题描述】:

不幸的是,我遇到了一个奇怪的错误。使用带有数据构造函数的中缀时会发生这种情况。

我是 Haskell 的新手。有人可以在这方面帮助我吗?

Prelude> data L a = Cons a (L a) | Emp deriving Show
Prelude> 10 `Cons` Emp
Cons 10 Emp
Prelude> 10 `Cons` 10 `Cons` Emp

<interactive>:43:1: error:
    • Non type-variable argument in the constraint: Num (L a)
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        it :: forall a. (Num a, Num (L a)) => L (L a)
Prelude> 10 `Cons` (10 `Cons` Emp) 
Cons 10 (Cons 10 Emp)
Prelude> 10 `Cons` 10 `Cons` Emp

<interactive>:45:1: error:
    • Non type-variable argument in the constraint: Num (L a)
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        it :: forall a. (Num a, Num (L a)) => L (L a)
Prelude> data L a = Emp | Cons a (L a)  deriving Show
Prelude> 10 `Cons` 10 `Cons` Emp

<interactive>:47:1: error:
    • Non type-variable argument in the constraint: Num (L a)
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        it :: forall a. (Num a, Num (L a)) => L (L a)
Prelude> 

【问题讨论】:

  • 如您所见,问题在于关联性。即使它不是完全重复的,这里的答案也完美地解释了这种行为以及如何解决它:stackoverflow.com/questions/8139066/…
  • Cons 需要是右关联运算符。

标签: haskell infix-notation


【解决方案1】:

您要做的是使用中缀运算符编写以下Cons 10 (Cons 10 Emp)

当您使用反引号 (`) 使普通函数中缀时,中缀运算符是左关联的。这意味着:

λ> 10 `Cons` 10 `Cons` Emp

如下括号:

λ> ((10 `Cons` 10) `Cons` Emp)

虽然你希望它是:

λ> 10 `Cons` ( 10 `Cons` Emp)

因为这等于Cons 10 (Cons 10 Emp)

这当然是右结合,因此你需要明确地用括号括起来。

Markus Mayr 链接了引用 Haskell 报告的 QA

【讨论】:

    【解决方案2】:

    您可以将数据构造函数定义为右关联,

    infixr 5 `Cons`
    
    data L a = Cons a (L a) | Emp deriving Show
    

    然后它将按您的预期工作。

    main = print $ (21::Int) `Cons` 42 `Cons` Emp
    
    -- => Cons 21 (Cons 42 Emp)
    

    【讨论】:

    • 我可以避免5 infixr 5 ` Cons like infixr `Cons 吗?
    • 你需要给它一些的偏好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    相关资源
    最近更新 更多