-- The power function, two ways

-- power x n computes x to the nth power for n >= 0

power :: Int -> Int -> Int
power x 0 = 1
power x n = x * power x (n - 1)

-- tail recursive form

powerTR :: Int -> Int -> Int
powerTR x n = powerTRLoop x n 0 1

powerTRLoop x n i result =
    if i == n
    then result
    else powerTRLoop x n (i + 1) (x * result)

-- With "proper" tail call optimization,
-- powerTR + powerTRLoop compiles like this (Python code):
--
-- i = 0
-- result = 1
-- while i != n:
--     result = x * result
--     i = i + 1 
-- return result
--
-- There is no use of the stack.
