【问题标题】:Haskell implement Show for data type with UArrayHaskell 使用 UArray 实现数据类型的 Show
【发布时间】:2021-05-04 22:48:07
【问题描述】:

我正在尝试为我的数据类型实现 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)]

使用参数化类型时我到底做错了什么?

【问题讨论】:

    标签: haskell generics types typeclass


    【解决方案1】:

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

    instance (IArray UArray a, Show a) => Show (Heap a) where
      show (Heap i a) = show a
    

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

    【讨论】:

    • 谢谢,我需要的语言扩展是{-# LANGUAGE FlexibleContexts, UndecidableInstances #-}。为什么我需要IArray UArray a 约束?
    • @mattematt 你需要它,因为UArrayShow 实例需要它(而该实例需要它,因为它调用boundsassocs)。查看实例列表及其上下文hereShow 实例列在底部附近。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    相关资源
    最近更新 更多