繁体   English   中英

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.

发生了几件事-第一个解决方案:

printMV :: MonadIO m => Show a => PrimMonad m => MV.MVector (PrimState m) a -> m ()
printMV v = do
    fv <- V.freeze v
    liftIO $ print fv

所以问题:

  • freeze本身就是一个m动作,所以它需要被绑定
  • liftIO需要一个MonadIO实例
  • 为了Show Vector a - a也必须在 class 中

你的第二个版本是相似的:

printMV2 :: Show a => MV.IOVector a -> IO ()
printMV2 v = V.freeze v >>= print
  • a Show实例
  • 需要>>= V.freeze的结果(与上面相同 - 隐式do此操作)
  • 这里不需要liftIO ,因为你已经在里面了

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM