3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Haskell の配列多すぎワロタ事件簿 1(STVector 編)

Last updated at Posted at 2017-01-14

それはある日起こった

Yesod での Web アプリ作成も一段落し、
Haskell 力を向上させるべく、競プロに勤しんでいた。
ある時「配列用意して破壊的操作したら余裕だぜ!」という問題に出会い、
調べてみた矢先だった。
配列の種類が大量にあるではないか・・・

immutable mutable
IArray STArray
Vector MVector

さらには boxed, unboxed、Data.Array は古い、行列は Repa(標準では使えない)やら、
何これ・・・どれをどういう時使うんだ・・・
とりあえず、mutable の Vector が速いらしいのでテストしてみることにした!

import Control.Monad
import Control.Monad.ST
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM

main :: IO ()
main = print $ V.toList $ sideEffect [0..100]

sideEffect :: [Int] -> V.Vector Int
sideEffect as = runST $ do
        vec <- V.thaw $ V.fromList as
        forM_ [0..10] $ \x -> VM.unsafeWrite vec x 2
        loop 0 vec
        V.freeze vec
    where
        loop i v = when (i < VM.length v) $ do
            VM.unsafeWrite v i 1
            loop (i + 1) v
  • List から Vector に変換
  • immutable, mutable の相互変換
  • 再帰を使ったループ処理
  • for(map 的な)ループ処理

これは便利そうだ\(^o^)/
次は STArray を試してみる予定♪

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?