計算機科学のブログ

関数型プログラミングの基礎 クロージャと部分的用 二項関数、引数、待機

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

コード

-- Q5-2
binaryPartialApplication :: (t1 -> t2 -> t3) -> t1 -> t2 -> t3
binaryPartialApplication binaryFunction x =
    \y -> binaryFunction x y

plus2x :: Integer -> Integer
plus2x = binaryPartialApplication (+) 2

minus2x :: Integer -> Integer
minus2x = binaryPartialApplication (-) 2

mul2x :: Integer -> Integer
mul2x = binaryPartialApplication (*) 2

div2x :: Double -> Double
div2x = binaryPartialApplication (/) 2

入出力結果(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 sample2
[1 of 1] Compiling Main             ( sample2.hs, interpreted )
Ok, one module loaded.
(0.01 secs,)
*Main
λ> plus2x 0
2
it :: Integer
(0.01 secs, 62,136 bytes)
*Main
λ> plus2x 1
3
it :: Integer
(0.00 secs, 59,688 bytes)
*Main
λ> plus2x 5
7
it :: Integer
(0.00 secs, 59,688 bytes)
*Main
λ> plus2x (-1)
1
it :: Integer
(0.00 secs, 59,736 bytes)
*Main
λ> plus2x (-5)
-3
it :: Integer
(0.00 secs, 60,504 bytes)
*Main
λ> minus2x 0
2
it :: Integer
(0.00 secs, 59,808 bytes)
*Main
λ> minus2x 1
1
it :: Integer
(0.00 secs, 59,688 bytes)
*Main
λ> minus2x 5
-3
it :: Integer
(0.00 secs, 60,456 bytes)
*Main
λ> minus2x (-1)
3
it :: Integer
(0.00 secs, 59,736 bytes)
*Main
λ> minus2x (-5)
7
it :: Integer
(0.00 secs, 59,736 bytes)
*Main
λ> mul2x 0
0
it :: Integer
(0.00 secs, 59,808 bytes)
*Main
λ> mul2x 1
2
it :: Integer
(0.00 secs, 59,672 bytes)
*Main
λ> mul2x 2
4
it :: Integer
(0.00 secs, 59,688 bytes)
*Main
λ> mul2x 5
10
it :: Integer
(0.00 secs, 60,424 bytes)
*Main
λ> mul2x (-1)
-2
it :: Integer
(0.00 secs, 60,504 bytes)
*Main
λ> mul2x (-5)
-10
it :: Integer
(0.00 secs, 61,240 bytes)
*Main
λ> div2x 0
Infinity
it :: Double
(0.00 secs, 65,768 bytes)
*Main
λ> div2x 1
2.0
it :: Double
(0.00 secs, 62,584 bytes)
*Main
λ> div2x 2
1.0
it :: Double
(0.00 secs, 62,624 bytes)
*Main
λ> div2x 5
0.4
it :: Double
(0.00 secs, 62,600 bytes)
*Main
λ> div2x (-1)
-2.0
it :: Double
(0.00 secs, 63,344 bytes)
*Main
λ> div2x (-5)
-0.4
it :: Double
(0.00 secs, 63,320 bytes)
*Main
λ> :quit
Leaving GHCi.
%