Advertisement
Guest User

Untitled

a guest
May 4th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.41 KB | None | 0 0
  1. // 1
  2. let rec sumList xs =
  3.     match xs with
  4.     | []    -> 0
  5.     | y::ys -> y + sumList ys // w y jest pierwszy element, w ys reszta listy
  6.  
  7. [1..1000000] |> sumList // stack overflow
  8.  
  9.  
  10. // 2
  11.  
  12. let sumListTailRecursive xs =
  13.     let rec sumListTailRecHelper accumulator xs =
  14.         match xs with
  15.         | []    -> accumulator
  16.         | y::ys -> sumListTailRecHelper (accumulator+y) ys
  17.     sumListTailRecHelper 0 xs
  18.  
  19. [1..10000000] |> sumListTailRecursive
  20.  
  21. // pomiar wydajności
  22.  
  23. let sumListIter xs =
  24.     let mutable sum = 0
  25.     for a in xs do
  26.         sum <- sum + a
  27.     sum
  28.  
  29. let l = [for a in 1..10000 -> a]
  30.  
  31. let stopWatch = System.Diagnostics.Stopwatch.StartNew()
  32. for _ in 1..100000 do
  33.      l |> sumList |> ignore
  34.  
  35. stopWatch.Stop();
  36. printfn "Rekurencja: %f" stopWatch.Elapsed.TotalMilliseconds
  37.  
  38. let stopWatch2 = System.Diagnostics.Stopwatch.StartNew()
  39. for _ in 1..100000 do
  40.      l |> sumListTailRecursive |> ignore
  41.  
  42. stopWatch2.Stop();
  43. printfn "Rekurencja ogonowa: %f" stopWatch2.Elapsed.TotalMilliseconds
  44.  
  45. let stopWatch3 = System.Diagnostics.Stopwatch.StartNew()
  46. for _ in 1..100000 do
  47.      l |> sumListIter |> ignore
  48.  
  49. stopWatch3.Stop();
  50. printfn "Iteracyjnie: %f" stopWatch3.Elapsed.TotalMilliseconds
  51.  
  52. let stopWatch4 = System.Diagnostics.Stopwatch.StartNew()
  53. for _ in 1..100000 do
  54.      List.sum l |> ignore
  55.  
  56. stopWatch4.Stop();
  57. printfn "List.sum: %f" stopWatch4.Elapsed.TotalMilliseconds
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement