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

时间:2015-03-14 09:10:11

标签: debugging haskell 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

尝试从vec内打印getLength时遇到以下问题:

> 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时,我就可以在vec内打印出getLength

1 个答案:

答案 0 :(得分:1)

您可以使用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]