HaskellのI/O Hello World! IO型の紹介 アクション、ユーザー入力、フィボナッチ数
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT4(HaskellのI/O)、LESSON 21(Hello World!:IO型の紹介)、21.5(練習問題)Q21-2の解答を求めてみる。
コード
fibonacci :: Integer -> Integer
fibonacci 0 = 0
fibonacci 1 = 1
fibonacci n = fibonacci (n - 1) + fibonacci (n - 2)
main :: IO ()
main = do
s <- getLine
let n = read s
print (show (fibonacci n))
入出力結果(Terminal, Zsh)
% ghci
GHCi, version 8.10.5: 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 /.../.ghc/ghci.conf
Prelude
λ> :load sample2
[1 of 1] Compiling Main ( sample2.hs, interpreted )
Ok, one module loaded.
(0.10 secs,)
*Main
λ> main
0
"0"
it :: ()
(1.33 secs, 72,304 bytes)
*Main
λ> main
1
"1"
it :: ()
(0.43 secs, 69,632 bytes)
*Main
λ> main
2
"1"
it :: ()
(0.46 secs, 69,992 bytes)
*Main
λ> main
3
"2"
it :: ()
(1.02 secs, 70,384 bytes)
*Main
λ> main
4
"3"
it :: ()
(0.94 secs, 71,136 bytes)
*Main
λ> main
5
"5"
it :: ()
(0.63 secs, 72,280 bytes)
*Main
λ> main
6
"8"
it :: ()
(0.71 secs, 74,176 bytes)
*Main
λ> main
7
"13"
it :: ()
(0.77 secs, 78,024 bytes)
*Main
λ> main
8
"21"
it :: ()
(1.50 secs, 82,960 bytes)
*Main
λ> main
9
"34"
it :: ()
(0.61 secs, 90,936 bytes)
*Main
λ> main
10
"55"
it :: ()
(0.65 secs, 106,336 bytes)
*Main
λ> :quit
Leaving GHCi.
%