計算機科学のブログ

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

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

コード

lesson/app/Main.hs

module Main where

-- import Lib

getRequestUrl :: String -> String -> String -> String -> String
getRequestUrl host apiKey resource id =
  mconcat
    [ host,
      "/",
      resource,
      "/",
      id,
      "?token=",
      apiKey
    ]

genHostBuilder :: String -> String -> String -> String -> String
genHostBuilder host =
  \apikey resource id -> getRequestUrl host apikey resource id

exampleUrlBuilder :: String -> String -> String -> String
exampleUrlBuilder = genHostBuilder "http://example.com"

genApiRequestBuilder ::
  (String -> String -> String -> String) ->
  String ->
  String ->
  String ->
  String
genApiRequestBuilder hostBuilder apiKey resource =
  (\id -> hostBuilder apiKey resource id)

myExampleUrlBuilder :: String -> String
myExampleUrlBuilder =
  genApiRequestBuilder exampleUrlBuilder "1337hAsk3ll" "book"

main :: IO ()
main = do
  print $ myExampleUrlBuilder "1234"

入出力結果(Terminal, Zsh)

% stack build
lesson-0.1.0.0: unregistering (local file changes: app/Main.hs)
lesson> configure (lib + exe)
Configuring lesson-0.1.0.0...
lesson> build (lib + exe)
Preprocessing library for lesson-0.1.0.0..
Building library for lesson-0.1.0.0..
Preprocessing executable 'lesson-exe' for lesson-0.1.0.0..
Building executable 'lesson-exe' for lesson-0.1.0.0..
[2 of 2] Compiling Main
Linking .stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/lesson-exe/lesson-exe ...
lesson> copy/register
Installing library in /Users/…/lesson/.stack-work/install/x86_64-osx/a5829d6ca8811667d4ffdd748f7759062ecf791847477ad6a6eeecb84527ff42/9.0.2/lib/x86_64-osx-ghc-9.0.2/lesson-0.1.0.0-CIOIkpTgcfQI9akDJnwnSd
Installing executable lesson-exe in /Users/…/lesson/.stack-work/install/x86_64-osx/a5829d6ca8811667d4ffdd748f7759062ecf791847477ad6a6eeecb84527ff42/9.0.2/bin
Registering library for lesson-0.1.0.0..
% stack exec lesson-exe
"http://example.com/book/1234?token=1337hAsk3ll"
%