計算機科学のブログ

実践Haskell 効率的でステートフルな配列 UArrayとSTUArray、thaw関数、クロスオーバー

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT7(実践Haskell)、LESSON42(Haskellでの効率的でステートフルな配列)、42.6(練習問題)Q42-1の解答を求めてみる。

package.yaml

name:                st-lesson
version:             0.1.0.0
github:              "githubuser/st-lesson"
license:             BSD3
author:              "Author name here"
maintainer:          "example@example.com"
copyright:           "2022 Author name here"

extra-source-files:
- README.md
- ChangeLog.md

# Metadata used when publishing your package
# synopsis:            Short description of your package
# category:            Web

# To avoid duplicated efforts in documentation and dealing with the
# complications of embedding Haddock markup inside cabal files, it is
# common to point users to the README.md file.
description:         Please see the README on GitHub at <https://github.com/githubuser/st-lesson#readme>

dependencies:
- base >= 4.7 && < 5

library:
  source-dirs: src

executables:
  st-lesson-exe:
    main:                Main.hs
    source-dirs:         app
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - st-lesson
    - array

tests:
  st-lesson-test:
    main:                Spec.hs
    source-dirs:         test
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - st-lesson

コード

app/Main.hs

module Main where

import Control.Monad (forM_)
import Data.Array.ST (runSTUArray, thaw, writeArray)
import Data.Array.Unboxed (IArray (bounds), UArray, array, (!))

-- import Lib ()

nums :: [Int]
nums = [0 .. 4]

a1 :: UArray Int Int
a1 = array (0, 4) $ zip nums $ repeat 1

a2 :: UArray Int Int
a2 = array (0, 4) $ zip nums $ repeat 0

pair :: (UArray Int Int, UArray Int Int)
pair = (a1, a2)

crossOver :: (UArray Int Int, UArray Int Int) -> Int -> UArray Int Int
crossOver (a1, a2) index = runSTUArray $ do
  stArray <- thaw a1
  let end = (snd . bounds) a1
  forM_ [index .. end] $ \i -> do
    writeArray stArray i $ a2 ! i
  return stArray

main :: IO ()
main = do
  mapM_ print [a1, a2]
  print $ crossOver (a1, a2) 3

入出力結果(Terminal, Zsh)

% stack runghc app/Main.hs
array (0,4) [(0,1),(1,1),(2,1),(3,1),(4,1)]
array (0,4) [(0,0),(1,0),(2,0),(3,0),(4,0)]
array (0,4) [(0,1),(1,1),(2,1),(3,0),(4,0)]
%