简体   繁体   English

Haskell与runST和Data.Vector.Unboxed.Mutable一起崩溃

[英]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.MutablerunST使用时,该代码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. 但是没有成功。

  • Why does Haskell (7.8.3) crashes with the provided code? 为什么Haskell(7.8.3)会因提供的代码而崩溃?
  • How can I compute the test function using runST but outside of test ? 我怎样才能计算test使用功能runST ,但外面test Was reading at this but still not clear why it doesn't works. 在阅读在 ,但仍不清楚为什么它不工作。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM