gpt4 book ai didi

haskell - 有类型类限制时,如何在实例语句中指定类型?

转载 作者:行者123 更新时间:2023-12-05 01:11:38 25 4
gpt4 key购买 nike

我试图定义一个非常简单的数据结构,假设将 Infinity 元素添加到 Num 下的任何类型。我还将它放在定义的类 NumContainer 下,它有一个方法 fromNum 使用常规 Num 构造一个 NumWithInf >。代码非常简单。

data NumWithInf a = Infinity | Finite a deriving Show

class NumContainer k where
fromNum :: Num a => a -> k

instance Num a => NumContainer (NumWithInf a) where
fromNum x = Finite x

但是当我运行它时,GHCI 给了我以下错误:

hw.hs:7:24:
Could not deduce (a ~ a1)
from the context (Num a)
bound by the instance declaration at hw.hs:6:10-45
or from (Num a1)
bound by the type signature for
fromNum :: Num a1 => a1 -> NumWithInf a
at hw.hs:7:5-24
`a' is a rigid type variable bound by
the instance declaration at hw.hs:6:10
`a1' is a rigid type variable bound by
the type signature for fromNum :: Num a1 => a1 -> NumWithInf a
at hw.hs:7:5
In the first argument of `Finite', namely `x'
In the expression: Finite x
In an equation for `fromNum': fromNum x = Finite x
Failed, modules loaded: none.

我知道它说 Finite x 中的 x 不一定与签名 中的 a 具有相同的类型fromNum::Num a => a -> k。我应该如何指定它?

最佳答案

一个简单的解决方案(即不求助于奇特的类型系统技巧的解决方案)是让您的类使用类型 * -> * 而不是 *。实际上,这只是意味着您将其定义为:

class NumContainer k where
fromNum :: Num a => a -> k a -- Result type parametrised on `a`

然后实例变为:

instance NumContainer NumWithInf where
fromNum x = Finite x

请注意,实例中没有放置Num 约束的地方。无论如何这都是不必要的——fromNum 类型的约束已经足够好了。

关于haskell - 有类型类限制时,如何在实例语句中指定类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32304114/

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