HaskellのI/O Hello World! IO型の紹介 Maybeでのdo表記
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT4(HaskellのI/O)、LESSON 21(Hello World!:IO型の紹介)、21.5(練習問題)Q21-1の解答を求めてみる。
コード
import qualified Data.Map as Map
helloPerson :: String -> String
helloPerson name = "Hello" ++ " " ++ name ++ "!"
names :: Map.Map Integer [Char]
names = Map.fromList ([(1, "Haskell")])
maybeMain :: Maybe String
maybeMain = do
name <- Map.lookup 1 names
return (helloPerson name)
maybeMain1 :: Maybe String
maybeMain1 = do
name <- Map.lookup 2 names
return (helloPerson name)
入出力結果(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 sample1.hs
[1 of 1] Compiling Main ( sample1.hs, interpreted )
Ok, one module loaded.
(0.05 secs,)
*Main
λ> maybe
<interactive>:2:1: error:
Ambiguous occurrence ‘maybe’
It could refer to
either ‘Prelude.maybe’,
imported from ‘Prelude’ at sample1.hs:1:1
(and originally defined in ‘Data.Maybe’)
or ‘Main.maybe’, defined at sample1.hs:10:1
(0.00 secs,)
*Main
λ> :load sample1.hs
[1 of 1] Compiling Main ( sample1.hs, interpreted )
Ok, one module loaded.
(0.01 secs,)
*Main
λ> maybeMain
Just "Hello Haskell!"
it :: Maybe String
(0.03 secs, 80,224 bytes)
*Main
λ> :load sample1.hs
[1 of 1] Compiling Main ( sample1.hs, interpreted )
Ok, one module loaded.
(0.01 secs,)
*Main
λ> maybeMain
Just "Hello Haskell!"
it :: Maybe String
(0.00 secs, 77,528 bytes)
*Main
λ> maybeMain1
Nothing
it :: Maybe String
(0.01 secs, 64,512 bytes)
*Main
λ> :quit
Leaving GHCi.
%