【发布时间】:2016-06-10 14:46:22
【问题描述】:
test :: VM.MVector s Int -> Int
test x = runST $ do
a <- return x
VM.read a 0 -- Type error
我试图弄清楚如何不将 ST monad 中的所有内容放入单个函数中。如果我试图修改x 或从中返回一个值,编译器会抱怨可变向量的状态部分不匹配。
是否可以在 Haskell 中对传递的可变向量进行操作,还是我必须在对它们进行任何操作之前将它们冻结为不可变的对应物?
编辑:
这是实际的错误。
Couldn't match type `s1' with `s'
`s1' is a rigid type variable bound by
a type expected by the context: ST s1 Int at rjb.hs:17:12
`s' is a rigid type variable bound by
the type signature for test :: VM.MVector s Int -> Int
at rjb.hs:16:11
Expected type: VM.MVector
(Control.Monad.Primitive.PrimState (ST s1)) Int
Actual type: VM.MVector s Int
Relevant bindings include
a :: VM.MVector s Int (bound at rjb.hs:18:5)
x :: VM.MVector s Int (bound at rjb.hs:17:8)
test :: VM.MVector s Int -> Int (bound at rjb.hs:17:3)
In the first argument of `VM.read', namely `a'
In a stmt of a 'do' block: VM.read a 0
编辑:以下通过类型检查。
test :: VM.MVector (Control.Monad.Primitive.PrimState IO) Int -> IO (Int)
test x = VM.read x 0
我猜我也可以改变x 向量。所以……
【问题讨论】:
-
你能补充一下实际的错误吗?
-
a <- return x是多余的。这只是再次给你x。 -
@Carsten 添加了错误。
-
如果你包含你的导入会有所帮助。
-
如果你想改变一个单子向量,你必须返回一个单子值。这就是 monad 的全部意义:副作用必须出现在类型中。
VM.MVector s Int -> Int类型的函数必然是一个常量函数。
标签: haskell vector monads mutable