gpt4 book ai didi

haskell - 没有因使用 `X' 而产生的 (Show a) 实例

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

用这段代码

{-# LANGUAGE GADTs #-}
data X a where
X :: (Show a, Num a) => a -> X a

instance Show (X a) where
show (X x) = "X " ++ show x

instance Num (X a) where
fromInteger x = X $ fromInteger x

我收到这个错误:

No instance for (Show a) arising from a use of `X'
Possible fix:
add (Show a) to the context of the instance declaration
In the expression: X
In the expression: X $ fromInteger x
In an equation for `fromInteger': fromInteger x = X $ fromInteger x

谁能解释为什么我会收到此错误消息?

最佳答案

正确的解决方案是将约束添加到实例头,如下所示:

instance (Show a, Num a) => Num (X a) where
fromInteger x = X $ fromInteger x

例如,显然您不能将 X String 视为 Num

关于haskell - 没有因使用 `X' 而产生的 (Show a) 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24800796/

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