計算機科学のブログ

ほしい物リスト

Haskell - 実践Haskell - Haskellでの効率的でステートフルの配列 - UArrayとSTUArray

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

軽量マークアップ言語

st-lesson/package.yaml

name:                st-lesson
version:             0.1.0.0
github:              "githubuser/st-lesson"
license:             BSD-3-Clause
author:              "Author name here"
maintainer:          "example@example.com"
copyright:           "2025 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
- array

ghc-options:
- -Wall
- -Wcompat
- -Widentities
- -Wincomplete-record-updates
- -Wincomplete-uni-patterns
- -Wmissing-export-lists
- -Wmissing-home-modules
- -Wpartial-fields
- -Wredundant-constraints

library:
  source-dirs: src

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

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

コード

st-lesson/app/Main.hs

module Main (main) where

-- import Lib

import Control.Monad
import Data.Array.ST
import Data.Array.Unboxed

replaceZeros :: UArray Int Int -> UArray Int Int
replaceZeros vals = runSTUArray $ do
  stArray <- thaw vals
  let end = (snd . bounds) vals
  forM_ [0 .. end] $ \i -> do
    val <- readArray stArray i
    when (val == 0) $ do
      writeArray stArray i (-1)
  return stArray

myData :: UArray Int Int
myData = array (0, 5) $ zip [1 .. 5] [1, 0, 10, -10, 0]

main :: IO ()
main = do
  print myData
  print $ replaceZeros myData

入出力結果(Terminal, Zsh)

% stack run
...
array (0,5) [(0,0),(1,1),(2,0),(3,10),(4,-10),(5,0)]
array (0,5) [(0,-1),(1,1),(2,-1),(3,10),(4,-10),(5,-1)]
%