Question 4-2

Consider the following Haskell function.

pow2 0 = 1
pow2 n = 2 * pow2 (n - 1)
Convert it into an equivalent tail-recursive Haskell function.

Solution

pow2 n =
  let
    it 0 ret = ret
    it i ret = pow2 (i - 1) (ret * 2)
  in it n 1

Back to Quiz 4