Advertisement
Guest User

Untitled

a guest
Mar 1st, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.12 KB | None | 0 0
  1. -module(step5).
  2. -export([sum/1, sumT/1, product/1, productT/1, max/1, maxT/1]).
  3.  
  4. sum ([]) ->
  5.     0;
  6. sum ([X|Xs]) ->
  7.     X + sum(Xs).
  8.  
  9. sumT (Xs) ->
  10.     % 1. initialization
  11.     sumT(Xs, 0).
  12.  
  13. % 2. test/condition part/step (if something then return ...)
  14. sumT ([], S) ->
  15.     % 3. execution step
  16.     S;
  17.  
  18. % 2. test/condition part/step (if something other then return ...)
  19. sumT ([X|Xs], S) ->
  20. %       ^
  21. %       |
  22. %       4. incrementation part/step
  23.     % 3. execution step
  24.     sumT(Xs, X + S).
  25.  
  26. % My reason why we mutliple by 1:
  27. % it needs to be one because multiplying something by zero gives zero
  28. % and we multiply our accumulator by the product of an empty list
  29. %
  30. % Reason after reading others comments
  31. % Multiplying by one does not change value of multiplied element :)
  32. product ([]) ->
  33.     1;
  34. product ([X|Xs]) ->
  35.     X * product(Xs).
  36.  
  37. productT (Xs) ->
  38.     productT(Xs, 1).
  39.  
  40. productT ([], A) ->
  41.     A;
  42. productT ([X|Xs], A) ->
  43.     productT(Xs, A * X).
  44.  
  45. max([X]) ->
  46.     X;
  47. max([X|Xs]) ->
  48.     max(X, max(Xs)).
  49.  
  50. maxT([X|Xs]) ->
  51.     maxT(Xs, X).
  52.  
  53. maxT([X], MaxValue) ->
  54.     max(X, MaxValue);
  55.  
  56. maxT([X|Xs], MaxValue) ->
  57.     maxT(Xs, max(X, MaxValue)).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement