計算機科学のブログ

HaskellのI/O Hello World!:IO型の紹介 do表記 Maybe、return

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT4(HaskellのI/O)、LESSON21(Hello World!:IO型の紹介)、21.5(練習問題)Q21-1の解答を求めてみる。

コード

import Data.Map as Map

helloPerson :: String -> String
helloPerson name = mconcat ["Hello ", name, "!"]

names :: Map.Map Int String
names = Map.fromList [(1, "name1"), (2, "name2")]

maybeMain :: Maybe String
maybeMain = do
  name <- Map.lookup 1 names
  let statement = helloPerson name
  return statement

maybeMain1 :: Maybe String
maybeMain1 = do
  name <- Map.lookup 0 names
  let statement = helloPerson name
  return name

入出力結果(Terminal, Zsh)

% ghci    
GHCi, version 8.10.7: https://www.haskell.org/ghc/  :? for help
Loaded package environment from /Users/…/.ghc/x86_64-darwin-8.10.7/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 /Users/…/.ghc/ghci.conf
Prelude
λ> :load sample1
[1 of 1] Compiling Main             ( sample1.hs, interpreted )
Ok, one module loaded.
(0.10 secs,)
*Main
λ> maybeMain
Just "Hello name1!"
it :: Maybe String
(0.01 secs, 79,416 bytes)
*Main
λ> maybeMain
maybeMain   maybeMain1
λ> maybeMain1
Nothing
it :: Maybe String
(0.00 secs, 65,120 bytes)
*Main
λ> :quit
Leaving GHCi.
%