HaskellのI/O コマンドラインの操作と遅延I/O 遅延評価とユーザー入力
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT4(HaskellのI/O)、LESSON 22(コマンドラインの操作と遅延I/O)、22.4(練習問題)Q22-2の解答を求めてみる。
lesson/package.yaml
name: lesson
version: 0.1.0.0
github: "githubuser/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/lesson#readme>
dependencies:
- base >= 4.7 && < 5
- split
library:
source-dirs: src
executables:
lesson-exe:
main: Main.hs
source-dirs: app
ghc-options:
- -threaded
- -rtsopts
- -with-rtsopts=-N
dependencies:
- lesson
tests:
lesson-test:
main: Spec.hs
source-dirs: test
ghc-options:
- -threaded
- -rtsopts
- -with-rtsopts=-N
dependencies:
- lesson
コード
lesson/app/Main.hs
module Main where
import Lib (toKakugens)
main :: IO ()
main = do
userInput <- getContents
mapM_ print $ toKakugens $ lines userInput
lesson/src/Lib.hs
module Lib where
import Data.List.Split (splitOn)
kakugens :: [String]
kakugens =
[ "kakugen1",
"kakugen2",
"kakugen3",
"kakugen4",
"kakugen5"
]
toKakugens :: [String] -> [String]
toKakugens [] = []
toKakugens ("n" : _) = []
toKakugens (x : xs) = kakugens !! (read x - 1) : toKakugens xs
入出力結果(Terminal, Zsh)
% stack exec lesson-exe
1
"kakugen1"
2
"kakugen2"
3
"kakugen3"
4
"kakugen4"
5
"kakugen5"
6
lesson-exe: Prelude.!!: index too large
% stack exec lesson-exe
5
"kakugen5"
1
"kakugen1"
4
"kakugen4"
2
"kakugen2"
3
"kakugen3"
n
%