gpt4 book ai didi

Haskell如何打印可变向量

转载 作者:行者123 更新时间:2023-12-04 03:30:41 25 4
gpt4 key购买 nike

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(很惊讶没有显示实例)。所以我必须先将它freezVector。然后我遇到了类型错误:

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-action,所以需要绑定(bind)
  • liftIO 需要一个 MonadIO 实例
  • 为了让 Vector a 成为 Show - a 也必须在该类中

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

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

关于Haskell如何打印可变向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66892474/

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