計算機科学のブログ

関数型プログラミングの基礎 ファーストクラス関数 引数、戻り値、ディスパッチ、case式

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT1(関数型プログラミングの基礎)、LESSON 4(ファーストクラス関数)、4.4(練習問題)Q4-2の解答を求めてみる。

コード

dcOffice :: ([Char], [Char]) -> [Char]
dcOffice name =
    let nameText = fst name ++ " " ++ snd name ++ ", Esq"
    in nameText ++ " - PO BOX 123 - Whasington DC, 12345"

getLocationFunction :: [Char] -> ([Char], [Char]) -> [Char]
getLocationFunction location =
  case location of
    -- "ny" -> nyOffice
    -- "sf" -> sfOffice
    -- "reno" -> renoOffice
    "dc" -> dcOffice
    _ -> (\name -> fst name ++ " " ++ snd name)

addressLetter :: ([Char], [Char]) -> [Char] -> [Char]
addressLetter name location = 
    let locationFunction = getLocationFunction location
    in locationFunction name

入出力結果(Terminal, Zsh)

% ghci
GHCi, version 8.10.4: 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 /Users/kamimura/.ghc/ghci.conf
Prelude
λ> :load sample2
[1 of 1] Compiling Main             ( sample2.hs, interpreted )
Ok, one module loaded.
(0.01 secs,)
*Main
λ> addressLetter ("Bob", "Smith") "ab"
"Bob Smith"
it :: [Char]
(0.01 secs, 71,384 bytes)
*Main
λ> addressLetter ("Bob", "Smith") "dc"
"Bob Smith, Esq - PO BOX 123 - Whasington DC, 12345"
it :: [Char]
(0.00 secs, 104,712 bytes)
*Main
λ> :quit
Leaving GHCi.
%