2012年3月23日星期五

SICP exercises in Haskell (Section 2.1.3)


-- Section 2.1.3
-- Exercise 2.4
cons x y = \m -> m x y
car z = z (\p q -> p)
cdr z = z (\p q -> q)


-- Exercise 2.5
cons' a b = (2 ^ a) * (3 ^ b)
car' c = car'' c 0
  where car'' n count 
          | odd n = count
          | otherwise = car'' (n `div` 2) (count + 1)
cdr' c = cdr'' c 0
  where cdr'' n count
          | mod n 3 /= 0 = count
          | otherwise = cdr'' (n `div` 3) (count + 1)
                        
-- Exercise 2.6                        
-- zero f = \x -> x
zero = \f -> (\x -> x)        


-- add_1 n f = \x -> f ((n f) x)
add_1 n = \f -> (\x -> f ((n f) x))


-- one f = \x -> f x
one = \f -> (\x -> f x)


-- two f = \x -> f (f x)
two = \f -> (\x -> f (f x))


-- plus a b f = \x -> (a f . b f) x
plus a b = \f -> (\x -> (a f . b f) x)



没有评论:

发表评论