gpt4 book ai didi

Haskell 使用 UArray 为数据类型实现 Show

转载 作者:行者123 更新时间:2023-12-04 08:10:42 24 4
gpt4 key购买 nike

我正在尝试为我的数据类型实现 Show 类型类

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)]
使用参数化类型时我到底做错了什么?

最佳答案

只需将给定的约束添加到您的实例上下文中。像这样:

instance (IArray UArray a, Show a) => Show (Heap a) where
show (Heap i a) = show a
您可能需要一些语言扩展;编译器会告诉你哪些。

关于Haskell 使用 UArray 为数据类型实现 Show,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65981192/

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