Advertisement
Guest User

tail recursion

a guest
Mar 9th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 0.68 KB | None | 0 0
  1. (* Recursive functions witch do not build up a growing intermediate
  2.  * expression are known as tail recursive. The following example
  3.  * function takes an integer n and raises it to the power of x *)
  4.  
  5. (* not tail recursive *)
  6. let rec power n x =
  7.    match x with
  8.    | 0 -> 1
  9.    | 1 -> n
  10.    | _ -> n * power n (x - 1);;
  11.  
  12. (* how it works with power 2 3:
  13. power 2 3
  14. 2 * (power 2 2)
  15. 2 * (2 * (power 2 1))
  16. 2 * (2 * (2))
  17. 8
  18. *)
  19.  
  20. (* tail recursive *)
  21. let power n x =
  22.    let rec auxpow acc x =
  23.       match x with
  24.       | 0 -> acc
  25.       | _ -> auxpow (acc * n) (x-1)
  26.    in auxpow 1 x;;
  27.  
  28. (* how it works with power 2 3:
  29. power 2 3
  30. auxpow 1 3
  31. auxpow 2 2
  32. auxpow 4 1
  33. auxpow 8 0
  34. 8
  35. *)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement