Advertisement
Guest User

Untitled

a guest
Mar 9th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 0.51 KB | None | 0 0
  1. (* not tail recurisive *)
  2. let rec power n x =
  3.    match x with
  4.    | 0 -> 1
  5.    | 1 -> n
  6.    | _ -> n * power n (x - 1);;
  7.  
  8. (* how it works if (power 2 3):
  9. power 2 3
  10. 2 * (power 2 2)
  11. 2 * (2 * power 2 1)
  12. 2 * (2 * (2 * (power 2 0)
  13. 2 * (2 * (2 * 1)
  14. 8
  15. *)
  16.  
  17. (* tail recursive *)
  18. let power n x =
  19.    let rec auxpow acc x =
  20.       match x with
  21.       | 0 -> acc
  22.       | _ -> auxpow (acc * n) (x-1)
  23.    in auxpow 1 x;;
  24.  
  25. (* how it works if (power 2 3):
  26. power 2 3
  27. auxpow 1 3
  28. auxpow 2 2
  29. auxpow 4 1
  30. auxpow 8 0
  31. 8
  32. *)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement