gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:53:54 24 4
gpt4 key购买 nike

假设我有以下内容:

--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]

关于debugging - 在 cabal repl/ghci 中查看通用容器的数据内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29047261/

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