-- -- script: tail.es -- -- created: 14/8/97 by Andrew Rock -- -- purpose: experiments with tail recursion. -- print_mode = f -- fact :: Int -> Int -- -- fact n returns n! -- -- linear recursive implementation -- fact n = if n == 0 then 1 else n * fact (n-1) -- fact' :: Int -> Int -- -- fact' n returns n! -- -- tail recursive implementation -- fact' n = fact'' n 1 fact'' n p = if n == 0 then p else fact'' (n-1) (p * n) -- fib :: Int -> Int -- -- fib n returns the n'th Fibonacci number in the sequence 0, 1, 1, 2, 3, ... -- -- tree recursive implementation -- fib n = if n == 0 then 0 else if n == 1 then 1 else fib (n-1) + fib (n-2) -- fib' :: Int -> Int -- -- fib' n returns the n'th Fibonacci number in the sequence 0, 1, 1, 2, 3, ... -- -- tail recursive implementation -- fib' n = fib'' n 0 1 fib'' n a b = if n == 0 then a else fib'' (n-1) b (a+b)