Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 在另一个数据构造函数中写入STVector_Haskell_Vector - Fatal编程技术网

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