2017年2月23日木曜日

開発環境

関数プログラミング入門(Richard Bird (著)、山下伸夫 (翻訳)、オーム社)の第3章(数値)、3.7(チャーチ数)、練習問題3.7.1、3.7.2、3.7.3、3.7.4を取り組んでみる。

練習問題3.7.1、3.7.2、3.7.3、3.7.4

コード(Emacs)

type Cbool a = a -> a -> a

bool :: Cbool Bool -> Bool
bool cb = cb True False


type Cnum a = (a -> a) -> (a -> a)

natural :: Cnum Int -> Int
natural cn = cn (1+) 0

succ' :: Cnum a -> Cnum a
succ' cn f = f . cn f

zero, one, two :: Cnum a
zero _ = id
one = succ' zero
two = succ' one
three = succ' two

-- 3.7.1
-- isZero :: ((a -> a) -> (a -> a)) -> (a -> a -> a)
isZero :: Cnum a -> Cbool a
isZero cn n m = cn ((\x y -> x) m) n

-- 3.7.2
-- arrow2 :: (((a -> a) -> (a -> a)) -> ((a -> a) -> (a -> a))) -> ((a -> a) -> (a -> a)) -> ((a -> a) -> (a -> a))
arrow2 :: Cnum (a -> a)  -> Cnum a  -> Cnum a
arrow2 m n = m n

-- 3.7.3
times1 :: Cnum a -> Cnum a -> Cnum a
times1 cn dn = cn . dn

-- arrow1 :: ((Cnum a -> Cnum a) -> c) -> Cnum a -> c
-- arrow1 zero :: Cnum a -> Cnum a -> Cnum a
-- arrow1 :: ((Cnum a -> Cnum a) -> (Cnum a -> Cnum a)) -> Cnum a -> (Cnum a -> Cnum a)
-- arrow1 :: (Cnum (Cnum a)) -> Cnum a -> (Cnum a -> Cnum a)
arrow1 :: (Cnum (Cnum a)) -> Cnum a -> Cnum (a -> a)
arrow1 cn = cn . times1

-- 3.7.4
data Either a b = Left a | Right b

type Ceither a b c = (a -> c) -> (b -> c) -> c

left :: a -> Ceither a b c
left x c _ = c x

right :: b -> Ceither a b c
right x _ c = c x

main :: IO ()
main = do
  print (natural zero)
  print (natural one)
  print (natural two)
  print (natural three)
  print (bool (isZero zero))
  print (bool (isZero one))
  print (bool (isZero two))
  print (bool (isZero three))
  print (natural (arrow2 zero two))
  print (natural (arrow2 three two))
  print (natural (arrow2 two zero))  

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

$ runghc sample7.hs
0
1
2
3
True
False
False
False
1
8
0
$

0 コメント:

コメントを投稿