提问人:daydaynatation 提问时间:4/1/2021 最后编辑:Will Nessdaydaynatation 更新时间:4/1/2021 访问量:251
Haskell 如何打印可变向量
Haskell how to print mutable vector
问:
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Primitive
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as MV
fromList :: [a] -> IO (MV.IOVector a)
fromList = V.thaw . V.fromList
printMV :: PrimMonad m => MV.MVector (PrimState m) a -> m ()
printMV = liftIO . print . V.freeze
我想打印(很惊讶没有显示实例)。所以我必须首先.
然后我遇到了类型错误:MVector
freez
Vector
Algo/QuickSort.hs:12:11: error: …
• Couldn't match type ‘PrimState m’ with ‘PrimState m0’
Expected type: MV.MVector (PrimState m) a -> m ()
Actual type: MV.MVector (PrimState m0) a -> m ()
NB: ‘PrimState’ is a non-injective type family
The type variable ‘m0’ is ambiguous
• In the expression: liftIO . print . V.freeze
In an equation for ‘printMV’: printMV = liftIO . print . V.freeze
• Relevant bindings include
printMV :: MV.MVector (PrimState m) a -> m ()
(bound at /home/skell/btree/Algo/QuickSort.hs:12:1)
|
Compilation failed.
我也试过IOVector
printMV :: MV.IOVector a -> IO ()
printMV = liftIO . print . V.freeze
这次的错误不同:
Algo/QuickSort.hs:12:28: error: …
• Couldn't match type ‘PrimState m0’ with ‘RealWorld’
Expected type: MV.IOVector a -> m0 (V.Vector a)
Actual type: MV.MVector (PrimState m0) a -> m0 (V.Vector a)
The type variable ‘m0’ is ambiguous
• In the second argument of ‘(.)’, namely ‘V.freeze’
In the second argument of ‘(.)’, namely ‘print . V.freeze’
In the expression: liftIO . print . V.freeze
|
Compilation failed.
答:
4赞
Random Dev
4/1/2021
#1
有几件事正在发生 - 第一个解决方案:
printMV :: MonadIO m => Show a => PrimMonad m => MV.MVector (PrimState m) a -> m ()
printMV v = do
fv <- V.freeze v
liftIO $ print fv
所以问题:
freeze
本身就是一个 -action,所以它需要绑定m
liftIO
需要实例MonadIO
- 为了成为 - 也必须在那个班级
Vector a
Show
a
您的第二个版本类似:
printMV2 :: Show a => MV.IOVector a -> IO ()
printMV2 v = V.freeze v >>= print
- 需要实例
Show
a
- 需要的结果(与上面相同 - 隐式地这样做)
>>=
V.freeze
do
- 这里没有必要,因为你已经在其中了
liftIO
评论
Show
Show
show
IO
IO
vector
freeze
MVector
Foldable
Traversable
mapM_ print
Foldable
Traversable
Show
mapM_ (MV.read v >=> print) [0 .. MV.length v-1]
IO
MV
Data.Vector.Mutable
MV.unsafeRead
[0 .. MV.length v-1]