Permalink
Browse files

accidentally solved 1.18 instead of 1.17... now they're both done

  • Loading branch information...
1 parent 68b1c18 commit 14c85c6ea4459e15723a92a4c67f11cf0e83ebde @llimllib committed Jan 27, 2009
Showing with 12 additions and 6 deletions.
  1. +12 −6 haskell/sicp/chap1.hs
View
@@ -122,18 +122,24 @@ fast_expt_iter b n = _fast_expt_iter b n 1
| n `mod` 2 == 0 = _fast_expt_iter (b*b) (n `div` 2) a
| otherwise = _fast_expt_iter b (n-1) (a*b)
--- exercise 1.17
double :: (Num a) => a -> a
double x = x + x
-- in python I'd say if x % 2 != 0: raise SomeException; what's the haskell way?
halve :: (Integral a) => a -> a
halve x = x `div` 2
+-- exercise 1.17
m :: (Num a, Integral b) => a -> b -> a
m a 0 = 0
-m a b = m_ a b 0
- where m_ a 0 acc = acc
- m_ a b acc
- | b `mod` 2 == 0 = m_ (double a) (halve b) acc
- | otherwise = m_ a (b - 1) (acc + a)
+m a b | b `mod` 2 == 0 = double $ m a (halve b)
+ | otherwise = a + m a (b - 1)
+
+--exercise 1.18
+m' :: (Num a, Integral b) => a -> b -> a
+m' a 0 = 0
+m' a b = m_ a b 0
+ where m_ a 0 acc = acc
+ m_ a b acc
+ | b `mod` 2 == 0 = m_ (double a) (halve b) acc
+ | otherwise = m_ a (b - 1) (acc + a)

0 comments on commit 14c85c6

Please sign in to comment.