Advertisement
Guest User

Untitled

a guest
May 24th, 2015
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. import fpinscala.tailrec._
  2.  
  3. object Counting {
  4. def normal (n : Int) : Int =
  5. if (n == 0) 0
  6. else 1 + normal(n - 1)
  7.  
  8. def cps (n : Int) : Int = {
  9. def loop (i : Int, k : Int => TailRec[Int]) : TailRec[Int] =
  10. if (i == 0) k(0)
  11. else loop(i - 1, x => Suspend(() => k(1 + x)))
  12.  
  13. loop(n, t => Return(t)).run
  14. }
  15.  
  16. def accum (n : Int) : Int = {
  17. def loop (i : Int, a : Int) : Int =
  18. if (i == 0) a
  19. else loop(i - 1, a + 1)
  20.  
  21. loop(n, 0)
  22. }
  23.  
  24. def main(args : Array[String]) : Unit = {
  25. val n = 100000
  26. val s1 = System.currentTimeMillis()
  27. accum(n)
  28. println(System.currentTimeMillis() - s1)
  29.  
  30. val s2 = System.currentTimeMillis()
  31. cps(n)
  32. println(System.currentTimeMillis() - s2)
  33.  
  34. val s3 = System.currentTimeMillis()
  35. normal(n)
  36. println(System.currentTimeMillis() - s3)
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement