Last active
August 29, 2015 14:07
-
-
Save davejachimiak/15d6db663304647c633f to your computer and use it in GitHub Desktop.
SICP 1.11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- SICP 1.11 | |
-- | |
-- A function f is defined by the rule that f(n) = n if n < 3 and | |
-- f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n >= 3. Write a | |
-- procedure computes f by means of a recursive process. | |
-- | |
f :: Integer -> Integer | |
f n | |
| n < 3 = n | |
| otherwise = f (n - 1) + 2 * f (n - 2) + 3 * f (n - 3) | |
-- Write a procedure that computes f by means of an iterative | |
-- process. | |
fIterative :: Integer -> Integer | |
fIterative n = fIterative' n 2 1 0 3 | |
fIterative' :: Integer -> | |
Integer -> | |
Integer -> | |
Integer -> | |
Integer -> | |
Integer | |
fIterative' n n1 n2 n3 count | |
| n < 3 = n | |
| n == count = strippedAwayF n1 n2 n3 | |
| otherwise = | |
fIterative' n (strippedAwayF n1 n2 n3) n1 n2 (count + 1) | |
strippedAwayF :: Integer -> | |
Integer -> | |
Integer -> | |
Integer | |
strippedAwayF n1 n2 n3 = n1 + (n2 * 2) + (n3 * 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment