[英]Haskell crashes with runST and Data.Vector.Unboxed.Mutable
While learning and experimenting the use of Data.Vector.Unboxed.Mutable
with runST
came up with this code: 在学习和试验将
Data.Vector.Unboxed.Mutable
与runST
使用时,该代码runST
了以下代码:
{-# LANGUAGE BangPatterns #-}
import qualified Data.Vector.Unboxed.Mutable as UVM (unsafeNew, unsafeWrite, unsafeRead)
import Control.Monad.ST
test :: Int -> Int
test len = runST $ do
vec <- UVM.unsafeNew (len - 1)
let
fill !i
| i >= len = sumVec 0 0
| otherwise = do
UVM.unsafeWrite vec i i
fill (i + 1)
sumVec !k !total
| k >= len = return total
| otherwise = do
x <- UVM.unsafeRead vec k
sumVec (k + 1) (total + x)
fill 0
testParent = test 5
If I run this, Haskell stops working. 如果我运行此程序,Haskell将停止工作。 I came to this while trying to make this work:
我在尝试使此工作时来到这里:
test :: Int -> Int
test len = do
.
.
.
testParent = runST $ test 5
But with no success. 但是没有成功。
In this line: 在这一行:
vec <- UVM.unsafeNew (len - 1)
you are creating a vector of length len-1
. 您正在创建长度为
len-1
的向量。 But you are writing into indices 0 through len-1
so you need a vector of length len
. 但是您正在写索引0到
len-1
因此需要一个长度为len
的向量。
Change that to len
and it will work. 将其更改为
len
使用。
As to your second question, you can use runST
like this: 关于第二个问题,可以这样使用
runST
:
-- test now begins with the `do` statement
test len = do
vec <- UVM.unsafeNew len
...
main = print $ runST $ test 5
main now has to wrap the call to test in runST
. main现在必须将调用包装在
runST
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.