2017年2月19日日曜日

開発環境

関数プログラミング入門(Richard Bird (著)、山下伸夫 (翻訳)、オーム社)の第3章(数値)、3.3(畳み込み関数)、練習問題3.3.1、3.3.2、3.3.3、3.3.4を取り組んでみる。

練習問題3.3.1、3.3.2、3.3.3、3.3.4

コード(Emacs)

-- 3.3.1
-- foldn Succ Zero undefined = undefined

-- foldn Succ Zero Zero = Zero
-- foldn Succ Zero (Succ n)
-- = Succ (foldn Succ Zero n)
-- = Succ n


-- 3.3.2
-- m + Zero = m
-- Zero + m = m

-- m + (Succ n)
-- = Succ (m + n)
-- = Succ (n + m)
-- = Succ (foldn Succ n m)
-- = (Succ . foldn Succ n) m
-- = (foldn Succ (Succ n)) m
-- = foldn Succ (Succ n) m
-- = (Succ n) + m


-- 3.3.3
data Nat = Zero | Succ Nat deriving (Eq, Ord, Show)

(-) :: Nat -> Nat -> Nat
n - Zero = n
(Succ n) - (Succ m) = n Main.- m

(/) :: Nat -> Nat -> Nat
Zero / Succ _  = Zero
(Succ Zero) / (Succ Zero) = Succ Zero
m / n = Succ ((m Main.- n) Main./ n)

-- (n * Zero) / n
-- = Zero / n
-- = Zero

-- (n * (Succ m)) / n
-- = ((n * m) + n) / n
-- = Succ ((((n * m) + n) - n) / n)
-- = Succ ((n * m) / n)
-- = Succ m


-- 3.3.4
log :: Nat -> Nat
log (Succ Zero) = Zero
log m = Succ (Main.log (m Main./ (Succ (Succ Zero))))

-- log (2 ^ Zero)
-- = log (Succ Zero)
-- = Zero

-- log (2 ^ (Succ m))
-- = log (2 * (2 ^ m))
-- = Succ (log (2 ^ m))
-- = Succ m  

n0, n1, n10 :: Nat
n0 = Zero
n1 = Succ Zero
n10 = Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))))

main :: IO ()
main = do
  print (n10 Main./ (Succ n1))
  print (Main.log (n10 Main.- n1 Main.- n1))

入出力結果(Terminal, ghci, runghc)

$ runghc sample3.hs
Succ (Succ (Succ (Succ (Succ Zero))))
Succ (Succ (Succ Zero))
$

0 コメント:

コメントを投稿

Comments on Google+: