計算機科学のブログ

関数型プログラミングの基礎 クロージャと部分的用 if文、偶数、even関数

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT1(関数型プログラミングの基礎)、LESSON 5(クロージャと部分的用)、5.5(練習問題)、Q5-1の解答を求めてみる。

コード

-- Q5-1
ifEven :: Integral p => (p -> p) -> p -> p
ifEven f n =
    if even n
    then f n
    else n

ifEvenInc :: Integer -> Integer
ifEvenInc = ifEven (+ 1)

ifEvenDouble :: Integer -> Integer
ifEvenDouble = ifEven (* 2)

ifEvenSquare :: Integer -> Integer
ifEvenSquare = ifEven (\x -> x * x)

入出力結果(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 sample1
[1 of 1] Compiling Main             ( sample1.hs, interpreted )
Ok, one module loaded.
(0.07 secs,)
*Main
λ> ifEvenInc 0
1
it :: Integer
(0.05 secs, 62,256 bytes)
*Main
λ> ifEvenInc 1
1
it :: Integer
(0.00 secs, 59,816 bytes)
*Main
λ> ifEvenInc 5
5
it :: Integer
(0.00 secs, 59,816 bytes)
*Main
λ> ifEvenInc (-1)
-1
it :: Integer
(0.00 secs, 60,632 bytes)
*Main
λ> ifEvenInc (-2)
-1
it :: Integer
(0.00 secs, 60,696 bytes)
*Main
λ> ifEvenInc 10
11
it :: Integer
(0.00 secs, 60,616 bytes)
*Main
λ> ifEvenDouble 0
0
it :: Integer
(0.00 secs, 59,928 bytes)
*Main
λ> ifEvenDouble 1
1
it :: Integer
(0.00 secs, 59,816 bytes)
*Main
λ> ifEvenDouble 2
4
it :: Integer
(0.00 secs, 59,880 bytes)
*Main
λ> ifEvenDouble 5
5
it :: Integer
(0.00 secs, 59,816 bytes)
*Main
λ> ifEvenSquare 0
0
it :: Integer
(0.00 secs, 59,904 bytes)
*Main
λ> ifEvenSquare 1
1
it :: Integer
(0.00 secs, 59,816 bytes)
*Main
λ> ifEvenSquare 2
4
it :: Integer
(0.00 secs, 59,880 bytes)
*Main
λ> ifEvenSquare 5
5
it :: Integer
(0.00 secs, 59,816 bytes)
*Main
λ> ifEvenSquare 10
100
it :: Integer
(0.00 secs, 61,352 bytes)
*Main
λ> ifEvenSquare (-1)
-1
it :: Integer
(0.00 secs, 60,632 bytes)
*Main
λ> ifEvenSquare (-2)
4
it :: Integer
(0.00 secs, 59,928 bytes)
*Main
λ> :quit 
Leaving GHCi.
%