Advertisement
Guest User

Untitled

a guest
Feb 27th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. %% exercises for 2.6
  2.  
  3. -module(ex_2_6).
  4. -export([prod/1, max/1, prod_tc/1, max_tc/1]).
  5. -export([prod_test/0, max_test/0,prod_tc_test/0, max_tc_test/0]).
  6.  
  7. %% template:
  8. %% foo([]) -> .....;
  9. %% foo([X|Xs]) -> ... foo(Xs) ...
  10.  
  11. %% product of a list
  12. prod([]) -> 1;
  13. prod([N|Ns]) -> N * prod(Ns).
  14.  
  15. prod_test() ->
  16. 1 = prod([]),
  17. 6 = prod([1,2,3]),
  18. ok.
  19.  
  20. %% maximum of a list
  21. max([N]) -> N;
  22. max([N|Ns]) ->
  23. max(N, max(Ns)).
  24.  
  25. max_test() ->
  26. 1 = max([1]),
  27. 3 = max([1,2,3]),
  28. 3 = max([3,2,1]),
  29. 3 = max([2,3,1]),
  30. ok.
  31.  
  32.  
  33. %% tail-call examples
  34. prod_tc(Lst) -> prod_tc(Lst, 1).
  35.  
  36. prod_tc([],P) -> P;
  37. prod_tc([N|Ns],P) -> prod_tc(Ns, N*P).
  38.  
  39. prod_tc_test() ->
  40. 1 = prod_tc([]),
  41. 6 = prod_tc([1,2,3]),
  42. ok.
  43.  
  44.  
  45. max_tc([N|Ns]) -> max_tc(Ns,N).
  46.  
  47. max_tc([], M) -> M;
  48. max_tc([N|Ns], M) ->
  49. max_tc(Ns, max(N,M)).
  50.  
  51. max_tc_test() ->
  52. 1 = max_tc([1]),
  53. 3 = max_tc([1,2,3]),
  54. 3 = max_tc([3,2,1]),
  55. 3 = max_tc([2,3,1]),
  56. ok.
  57.  
  58. %% I think direct recursion is eaier to use. The desing of the
  59. %% fuction matches the data defintion more directly.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement