查看 cabal 中通用容器的数据内容 repl/ghci

Viewing data contents of generic container in cabal repl/ghci

假设我有以下内容:

--Main.hs
module Main where
import Data.Vector as V
import Test

main = do
  let v = V.fromList ([1,2]::[Int])
  print (getLength v)

和:

--Test.hs
module Test where
import Data.Vector as V

getLength :: (Show a) => V.Vector a -> Int
getLength vec = let l = V.length vec in -- line 6
  l

我在尝试从 getLength 中打印出 vec 时遇到以下问题:

> cabal repl
> :break Test 6
> main
Stopped at Test.hs:6:25-36
_result :: Int = _
vec :: Vector a = _
> vec
<interactive>:4:1:
    No instance for (Show a) arising from a use of ‘print’
    Cannot resolve unknown runtime type ‘a’
    Use :print or :force to determine these types
    Relevant bindings include
      it :: Vector a (bound at <interactive>:4:1)
    Note: there are several potential instances:
      instance Show Double -- Defined in ‘GHC.Float’
      instance Show Float -- Defined in ‘GHC.Float’
      instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
        -- Defined in ‘GHC.Real’
      ...plus 45 others
    In a stmt of an interactive GHCi command: print it

我试过使用 :force:print 但都没有用。奇怪的是,当 getLength 放在 Main.hs 中时,我可以毫无问题地从 getLength.

中打印出 vec

您可以使用toList获取基础数据:

λ :print vec
vec = (_t1::Vector a)
λ :force vec
vec = Data.Vector.Vector 0 2 _
λ :print vec
vec = Data.Vector.Vector 0 2 (_t2::GHC.Prim.Array# a)
λ let as = toList vec
λ :print as
as = (_t6::[a])
λ :force as
as = [1,2]
λ :print vec
vec = Data.Vector.Vector 0 2 (_t7::GHC.Prim.Array# Int)
λ :force vec
vec = Data.Vector.Vector 0 2 _
λ print vec
fromList [1,2]