gpt4 book ai didi

haskell - 与中缀一起使用时,约束错误中的非类型变量参数

转载 作者:行者123 更新时间:2023-12-02 01:51:16 25 4
gpt4 key购买 nike

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

我是 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>

最佳答案

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

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)

关于haskell - 与中缀一起使用时,约束错误中的非类型变量参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70315884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com