[英]Creating a random permutation of 1..N with Data.Vector.Unboxed.Mutable
[英]Haskell crashes with runST and Data.Vector.Unboxed.Mutable
在學習和試驗將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
如果我運行此程序,Haskell將停止工作。 我在嘗試使此工作時來到這里:
test :: Int -> Int
test len = do
.
.
.
testParent = runST $ test 5
但是沒有成功。
test
使用功能runST
,但外面test
? 在閱讀在此 ,但仍不清楚為什么它不工作。 在這一行:
vec <- UVM.unsafeNew (len - 1)
您正在創建長度為len-1
的向量。 但是您正在寫索引0到len-1
因此需要一個長度為len
的向量。
將其更改為len
使用。
關於第二個問題,可以這樣使用runST
:
-- test now begins with the `do` statement
test len = do
vec <- UVM.unsafeNew len
...
main = print $ runST $ test 5
main現在必須將調用包裝在runST
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.