LoginSignup
2
2

More than 5 years have passed since last update.

リストとIOUArray

Last updated at Posted at 2015-01-10

Haskellの実験メモです。

別のリストを作り続ける方法と、IOUArrayで書き替える方法を比較しました。

※ UArrayの存在は知っていますが、意図的にリストを使いました。

リスト

変更後のリストは作り直しているのでprint以外の副作用はありません。

writeList list index value =
    take index list ++ [value] ++ drop (index + 1) list

main = do
    let a = [1,2,3]
    print a

    let b = writeList a 0 9
    print b

    let c = writeList b 2 9
    print c
実行結果
[1,2,3]
[9,2,3]
[9,2,9]

IOUArray

書き換えで副作用が発生しています。

import Data.Array.IO

main = do
    a <- newListArray (0,2) [1,2,3] :: IO (IOUArray Int Int)
    print =<< getElems a

    writeArray a 0 9
    print =<< getElems a

    writeArray a 2 9
    print =<< getElems a
実行結果
[1,2,3]
[9,2,3]
[9,2,9]
2
2
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
2
2