コンテキストでの型の操作 Monad型クラス bind演算子:>>=、IO
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT5(コンテキストでの型の操作)、LESSON 30(Monad型クラス)、30.2(bind演算子:»=)のクイックチェック 30-3の解答を求めてみる。
コード
readInt :: IO Int
readInt = read <$> getLine
printDouble :: Int -> IO ()
printDouble n = print (n*2)
readIntAndPrintDouble :: IO ()
readIntAndPrintDouble = readInt >>= printDouble
main :: IO ()
main = readIntAndPrintDouble
入出力結果(Terminal, Zsh)
% runghc sample03.hs
2
4
kamimura@MacBook lesson30 % ghci
GHCi, version 8.10.6: https://www.haskell.org/ghc/ :? for help
macro 'doc' overwrites builtin command. Use ':def!' to overwrite.
(0.00 secs, 0 bytes)
(0.00 secs, 0 bytes)
Loaded GHCi configuration from /Users/…/.ghc/ghci.conf
Prelude
λ> :load sample03.hs
[1 of 1] Compiling Main ( sample03.hs, interpreted )
Ok, one module loaded.
(0.03 secs,)
*Main
λ> main
0
0
it :: ()
(1.63 secs, 71,248 bytes)
*Main
λ> main
1
2
it :: ()
(1.14 secs, 68,608 bytes)
*Main
λ> main
2
4
it :: ()
(0.28 secs, 68,608 bytes)
*Main
λ> main
-1
-2
it :: ()
(1.51 secs, 73,584 bytes)
*Main
λ> main
-2
-4
it :: ()
(0.90 secs, 73,584 bytes)
*Main
λ> :quit
Leaving GHCi.
%