HaskellのI/O 式の読み込み、計算、加算と乗算、getLine関数、Data.List.Splitモジュール、splitOn関数
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT4(HaskellのI/O)、LESSON 22(コマンドラインの操作と遅延I/O)、22.4(練習問題)のQ22-1の解答を求めてみる。
コード
import Data.List.Split
calc :: [String] -> Maybe Double
calc (a:"+":[b]) = Just (read a + read b)
calc (a:"*":[b]) = Just (read a * read b)
calc _ = Nothing
unwrap :: Maybe Double -> String
unwrap (Just a) = show a
unwrap Nothing = "Invalid input"
main :: IO ()
main = do
print "Input(a (+|*) b)"
line <- getLine
let ops = splitOn " " line
let result = unwrap (calc ops)
print result
入出力結果(Terminal, Zsh)
% ghci
GHCi, version 8.10.5: https://www.haskell.org/ghc/ :? for help
Loaded package environment from /.../.ghc/x86_64-darwin-8.10.5/environments/default
macro 'doc' overwrites builtin command. Use ':def!' to overwrite.
(0.00 secs, 0 bytes)
(0.00 secs, 0 bytes)
Loaded GHCi configuration from /.../.ghc/ghci.conf
Prelude
λ> :load simple.calc.hs
[1 of 1] Compiling Main ( simple.calc.hs, interpreted )
Ok, one module loaded.
(0.08 secs,)
*Main
λ> main
"Input(a (+|*) b)"
1 + 2
"3.0"
it :: ()
(1.59 secs, 106,296 bytes)
*Main
λ> main
"Input(a (+|*) b)"
1 * 2
"2.0"
it :: ()
(1.42 secs, 100,816 bytes)
*Main
λ> main
"Input(a (+|*) b)"
1 / 2
"Invalid input"
it :: ()
(2.38 secs, 99,712 bytes)
*Main
λ> main
"Input(a (+|*) b)"
1 + 2
"Invalid input"
it :: ()
(3.47 secs, 101,840 bytes)
*Main
λ> main
"Input(a (+|*) b)"
-1^?2
"Invalid input"
it :: ()
(4.32 secs, 97,424 bytes)
*Main
λ> main
"Input(a (+|*) b)"
-1 + 2
"1.0"
it :: ()
(7.04 secs, 105,296 bytes)
*Main
λ> main
"Input(a (+|*) b)"
-2 * -3
"6.0"
it :: ()
(4.51 secs, 109,488 bytes)
*Main
λ> :quit
Leaving GHCi.
%