Haskell 在另一个数据构造函数中写入STVector
我正在尝试编写一个动态的Haskell 在另一个数据构造函数中写入STVector,haskell,vector,Haskell,Vector,我正在尝试编写一个动态的STVector,当向量容量超过时,它将在ST monad中展开(对于命令式算法)。为此,我创建了一个新的数据构造函数,它包装了一个STVector,并添加了一个Int,以跟踪最后插入的向量。问题是我从typechecker得到错误,因为我的状态实现似乎不正确。我将非常感谢以下示例中关于如何正确管理DVec s状态的提示: {-# LANGUAGE BangPatterns #-} module Test where import Data.Vector.Unboxed.
STVector
,当向量容量超过时,它将在ST monad
中展开(对于命令式算法)。为此,我创建了一个新的数据构造函数,它包装了一个STVector
,并添加了一个Int
,以跟踪最后插入的向量。问题是我从typechecker得到错误,因为我的状态实现似乎不正确。我将非常感谢以下示例中关于如何正确管理DVec s
状态的提示:
{-# LANGUAGE BangPatterns #-}
module Test where
import Data.Vector.Unboxed.Mutable as MU
import Control.Monad.ST as ST
import Control.Monad.Primitive (PrimState)
import GHC.Float.RealFracMethods (int2Float)
type MVI1 s = MVector (PrimState (ST s)) Int
data DVec s = DV {-# UNPACK #-}!Int -- this one keeps track of index of last vector
(MVI1 s)
append :: DVec s -> Int -> ST s (DVec s)
append (DV i v) x = do
if i < MU.length v then MU.unsafeWrite v i x >> return $ DV (i+1) v
else MU.unsafeGrow v (floor $ 1.5 * (int2Float $ MU.length v)) >>= (\y -> MU.unsafeWrite y i x >> return $ DV (i+1) y)
问题是,
$
运算符的优先级最低,因此,它左边的所有内容都被视为一个函数。
不要使用return$DV(i+1)v
而使用return(DV(i+1)v)
我是怎么知道的?
我删除了您的类型注释,以查看ghci将确定什么类型。Ghci检测到具有此约束的类型
(Control.Monad.Primitive.PrimMonad((->)(DVec(PrimState m))
。这意味着存在一些错误,使Ghci认为正在使用的PrimMonad
也是一个函数。然后很明显,($)
是其背后的原因。问题在于$
运算符的优先级最低,因此,它左边的所有内容都被视为一个函数。
不要使用return$DV(i+1)v
而使用return(DV(i+1)v)
我是怎么知道的?
我删除了您的类型批注以查看ghci将确定什么类型。ghci检测到具有此约束的类型(Control.Monad.Primitive.PrimMonad((->)(DVec(PrimState m))
。这意味着存在一些错误,使ghci认为正在使用的PrimMonad
也是一个函数。然后很明显($)
是这背后的原因
Couldn't match type `s' with `PrimState ((->) (DVec s))'
`s' is a rigid type variable bound by
the type signature for append :: DVec s -> Int -> ST s (DVec s)
at B.hs:11:11
Expected type: MVector (PrimState ((->) (DVec s))) Int
Actual type: MVI1 s
In the first argument of `unsafeWrite', namely `y'
In the first argument of `(>>)', namely `unsafeWrite y i x'
In the expression: unsafeWrite y i x >> return