Haskell 使用 UArray 实现数据类型的显示

Haskell implement Show for data type with UArray

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

data Heap a = Heap {invariant :: a -> a -> Ordering
                   ,arr :: UArray Int a}

在此数据上使用显示时,我只希望它显示底层数组。我试过像这样实现表演:

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

您可能需要一些语言扩展;编译器会告诉你哪些。