Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. // Solution
  2.  
  3. // In this sample, the goal was to compute the length of the list
  4.  
  5. // Method 1: Library Function
  6.  
  7. let ourList =
  8. [
  9. 2;
  10. 4;
  11. 13;
  12. 26;
  13. 15;
  14. 29;
  15. 130;
  16. 0;
  17. -7;
  18. ]
  19.  
  20. let sum1 = List.sumBy(fun el ->
  21. if el % 13 = 0 then
  22. el
  23. else
  24. 0
  25. )
  26.  
  27. // Method 2: Recursion
  28. let rec sum2 = function
  29. | [] -> 0
  30. | h::t ->
  31. if h % 13 = 0 then sum2(t) + h
  32. else sum2(t)
  33.  
  34. // Method 3: Tail Rec
  35. let sum3 =
  36. let rec sum3' acc i = function
  37. | [] -> acc
  38. | h::t ->
  39. if i % 2 = 0 then sum3' (acc+h) (i+1) t
  40. else sum3' (acc) (i+1) t
  41. sum3' 0 0
  42.  
  43. let main =
  44. printfn "%10d simple" (sum1 ourList)
  45. printfn "%10d recursion" (sum2 ourList)
  46. printfn "%10d tail recursion" (sum3 ourList)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement