計算機科学のブログ

関数型プログラミングの基礎 クロージャと部分的用 APIで使用するURLの生成 単純化

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT1(関数型プログラミングの基礎)、LESSON 5(クロージャと部分的用)、5.2(例:APIで使用するURLの生成)のクイックチェック5-2、部分的用、クロージャの単純化のクイックチェック5-3の解答を求めてみる。

コード

-- クイックチェック5-2
genApiRequestBuilder :: (t1 -> t2 -> t3 -> t4) -> t1 -> t2 -> t3 -> t4
genApiRequestBuilder hostBuilder apiKey resource =
  \id -> hostBuilder apiKey resource id

-- クイックチェック5-3
getRequestUrl :: [Char] -> [Char] -> [Char] -> [Char] -> [Char]
getRequestUrl host apiKey resource id =
  host ++ "/" ++
  resource ++ "/" ++
  id ++
  "?token=" ++
  apiKey
-- 段階を経て作成
exampleUrlBuilder :: [Char] -> [Char] -> [Char] -> [Char]
exampleUrlBuilder = getRequestUrl "http://example.com"
myExampleUrlBuilder :: [Char] -> [Char] -> [Char]
myExampleUrlBuilder = exampleUrlBuilder "1337hAsk311"
myExampleBookUrlBuilder :: [Char] -> [Char]
myExampleBookUrlBuilder = myExampleUrlBuilder "book"

-- 一度で作成
myExampleBookUrlBuilder1 :: [Char] -> [Char]
myExampleBookUrlBuilder1 = getRequestUrl "http://example.com" "1337hAsk311" "book"

入出力結果(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 /.../.ghc/ghci.conf
Prelude
λ> :load sample02
[1 of 1] Compiling Main             ( sample02.hs, interpreted )
Ok, one module loaded.
(0.01 secs,)
*Main
λ> myExampleBookUrlBuilder "id0"
"http://example.com/book/id0?token=1337hAsk311"
it :: [Char]
(0.01 secs, 103,328 bytes)
*Main
λ> myExampleBookUrlBuilder1 "id1"
"http://example.com/book/id1?token=1337hAsk311"
it :: [Char]
(0.00 secs, 100,752 bytes)
*Main
λ> :quit 
Leaving GHCi.
%