我正在尝试为我的数据类型实现Show the类
data Heap a = Heap {invariant :: a -> a -> Ordering
,arr :: UArray Int a}当对这个数据使用show时,我只想让它显示底层的数组。我试着像这样实现Show:
instance Show a => Show (Heap a) where
show (Heap i a) = show a但这给了我以下错误:
Heap.hs:12:21: error:
• Could not deduce (IArray UArray a) arising from a use of ‘show’
from the context: Show a
bound by the instance declaration at Heap.hs:11:10-32
• In the expression: show a
In an equation for ‘show’: show (Heap i a) = show a
In the instance declaration for ‘Show (Heap a)’
|
12 | show (Heap i a) = show a
| ^^^^^^我认为问题与参数化类型有关,因为如果我使用Int而不是a,就像下面的代码一样,它工作得很好:
data Heap = Heap {invariant :: Int -> Int -> Bool
,arr :: UArray Int Int}
instance Show Heap where
show (Heap i a) = show a在GHCI中
λ > Heap (>) (array (1,10) [])
array (1,10) [(1,0),(2,0),(3,0),(4,0),(5,0),(6,0),(7,0),(8,0),(9,0),(10,0)]在使用参数化类型时,我到底做错了什么?
发布于 2021-02-01 00:03:11
只需将给定的约束添加到您的实例上下文。如下所示:
instance (IArray UArray a, Show a) => Show (Heap a) where
show (Heap i a) = show a您可能需要一些语言扩展;编译器会告诉您哪些扩展。
https://stackoverflow.com/questions/65981192
复制相似问题