計算機科学のブログ

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

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

コード

sample.hs

import qualified Data.Map as Map
main :: IO ()
main = do
    mapM_ print [maybeMain1, maybeMain2]

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

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

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

names :: Map.Map Int String
names = Map.fromList [(1, "haskell")]

入出力結果(Terminal, Zsh)

% runghc sample.hs
Just "Hello, haskell!"
Nothing
%