2012年3月21日星期三

SICP exercises in Haskell (Section 2.1.1)


-- Section 2.1.1
-- Exercise 2.1
type Rat = (Int, Int)


make_rat :: Int -> Int -> Rat
make_rat x y 
  | x < 0 && y < 0 = make_rat (-x) (-y)
  | x > 0 && y < 0 = make_rat (-x) (-y)
  | otherwise     = (x `div` d, y `div` d)
  where d = gcd x y                    


number :: Rat -> Int
number rat = fst rat


demon :: Rat -> Int
demon rat = snd rat


print_rat :: Rat -> String
print_rat rat = show (number rat) ++ 
                "/" ++ show (demon rat)

没有评论:

发表评论