計算機科学のブログ

実践Haskell 効率的でステートフルな配列 UArray型を使って効率のよい配列を作成する UArrayを作成する

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT7(実践Haskell)、LESSON42(Haskellでの効率的でステートフルな配列)、42.1(UArray型を使って効率のよい配列を作成する)、UArrayを作成する、クイックチェック 42-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 Data.Array.Unboxed (UArray, array)
import Lib ()

qcArray :: UArray Int Bool
qcArray = array (0, 4) $ zip [1, 2] $ repeat True

main :: IO ()
main = do
  print qcArray

入出力結果(Terminal, Zsh)

% stack build
st-lesson-0.1.0.0: unregistering (local file changes: .stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/autogen/Paths_st_lesson.hs .stack-work/dist/x86_6...)
st-lesson> build (lib + exe)
Preprocessing library for st-lesson-0.1.0.0..
Building library for st-lesson-0.1.0.0..
Preprocessing executable 'st-lesson-exe' for st-lesson-0.1.0.0..
Building executable 'st-lesson-exe' for st-lesson-0.1.0.0..
[2 of 2] Compiling Main
Linking .stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/st-lesson-exe/st-lesson-exe ...
st-lesson> copy/register
Installing library in /Users/…/st-lesson/.stack-work/install/x86_64-osx/ab5b3640cd39493075c57a4e40b7505b193ab716e242cc230234f0b245ae2353/9.0.2/lib/x86_64-osx-ghc-9.0.2/st-lesson-0.1.0.0-JrEFrkWsA9w76pwrA55rwI
Installing executable st-lesson-exe in /Users/…/st-lesson/.stack-work/install/x86_64-osx/ab5b3640cd39493075c57a4e40b7505b193ab716e242cc230234f0b245ae2353/9.0.2/bin
Registering library for st-lesson-0.1.0.0..
% stack exec st-lesson-exe   
array (0,4) [(0,False),(1,True),(2,True),(3,False),(4,False)]
%