関数型プログラミングの基礎 ファーストクラス関数 戻り値としての関数、ディスパッチ
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT1(関数型プログラミングの基礎)、LESSON 4(ファーストクラス関数)、4.4(練習問題)Q4-2の解答を求めてみる。
コード
lesson/app/Main.hs
module Main where
import Data.List (sortBy)
-- import Lib ()
dcOffice :: (String, String) -> String
dcOffice (fname, lname) =
mconcat
[ fname,
" ",
lname,
", Esq. Washington, DC"
]
getLocationFunction :: String -> (String, String) -> String
getLocationFunction location =
case location of
"dc" -> dcOffice
_ ->
( \(fname, lname) ->
mconcat
[ fname,
" ",
lname
]
)
addressLetter :: (String, String) -> String -> String
addressLetter name location =
let locationFunction = getLocationFunction location
in locationFunction name
names :: [(String, String)]
names =
[ ("Ian", "Curtis"),
("Bernard", "Sumner"),
("Peter", "Hook"),
("Stephen", "Morris"),
("Ian", "Sumner"),
("Bernard", "Sumner")
]
main :: IO ()
main = do
mapM_ print names
mapM_ print $
addressLetter
<$> names
<*> ["dc", ""]
入出力結果(Terminal, Zsh)
% stack runghc app/Main.hs
("Ian","Curtis")
("Bernard","Sumner")
("Peter","Hook")
("Stephen","Morris")
("Ian","Sumner")
("Bernard","Sumner")
"Ian Curtis, Esq. Washington, DC"
"Ian Curtis"
"Bernard Sumner, Esq. Washington, DC"
"Bernard Sumner"
"Peter Hook, Esq. Washington, DC"
"Peter Hook"
"Stephen Morris, Esq. Washington, DC"
"Stephen Morris"
"Ian Sumner, Esq. Washington, DC"
"Ian Sumner"
"Bernard Sumner, Esq. Washington, DC"
"Bernard Sumner"
%