Advertisement
Guest User

tail recursion

a guest
Mar 9th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 0.75 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 4:
  13. power 2 4;;
  14. 2 * (power 2 3)
  15. 2 * (2 * (power 2 2))
  16. 2 * (2 * (2 * (power 2 1)))
  17. 2 * (2 * (2 * 2))
  18. 2 * (2 * 4)
  19. 2 * 8
  20. 16
  21. *)
  22.  
  23. (* tail recursive *)
  24. let power n x =
  25.    let rec auxpow acc x =
  26.       match x with
  27.       | 0 -> acc
  28.       | _ -> auxpow (acc * n) (x-1)
  29.    in auxpow 1 x;;
  30.  
  31. (* how it works with power 2 4:
  32. power 2 4;;
  33. auxpow 1 4
  34. auxpow 2 3
  35. auxpow 4 2
  36. auxpow 8 1
  37. auxpow 16 0
  38. 16
  39. *)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement