計算機科学のブログ

関数型プログラミングの基礎 ファーストクラス関数 引数としての関数 引数としてのラムダ式

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT1(関数型プログラミングの基礎)、LESSON 4(ファーストクラス関数)、4.1(引数としての関数)、引数としてのラムダ式、クイックチェック 4-1の解答を求めてみる。

コード

lesson/app/Main.hs

module Main where

import Lib (ifEven)

main :: IO ()
main = do
  mapM_
    ( \n ->
        putStrLn $
          mconcat
            [ "ifEven (\\x -> x^3) ",
              show n,
              " -> ",
              show $ ifEven (\x -> x ^ 3) n
            ]
    )
    [-4 .. 5]

入出力結果(Terminal, Zsh)

% stack build          
lesson-0.1.0.0: unregistering (local file changes: app/Main.hs)
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
ifEven (\x -> x^3) -4 -> -64
ifEven (\x -> x^3) -3 -> -3
ifEven (\x -> x^3) -2 -> -8
ifEven (\x -> x^3) -1 -> -1
ifEven (\x -> x^3) 0 -> 0
ifEven (\x -> x^3) 1 -> 1
ifEven (\x -> x^3) 2 -> 8
ifEven (\x -> x^3) 3 -> 3
ifEven (\x -> x^3) 4 -> 64
ifEven (\x -> x^3) 5 -> 5
%