erlang - Factorial calculation between two integers -


the function supposed calculate sum of integers between 2 integers n , m n <= m.

sum(n, m) ->     if         n+1 =< m -> n + sum((n+1), m);         n =< m -> n;         n > m -> 'n must <= m'     end. 

is there better way this? can put second statement inside first?

some comments , proposition

-module (ex).  -compile([export_all]).  %% comments on proposal sum1(n, m) ->     if  %% if statement not popular in erlang since not realy if in java or c         n+1 =< m -> n + sum1((n+1), m);         n =< m -> n;         n > m -> 'n must <= m' %% don't this, creates useless atoms limited                                   %% in number , cannot destroyed during vm life     end.   %% second solution, tail recursive sum2(n,m) when n > m -> {error,"n must <= m"}; %% instead use guard return tuple                                                   %% standard atom + string reason sum2(n,m) -> sum2(n,m,0). %% use accumulator create tail recursive function                           %% not important example usage                           %% avoid stack overflow :o)  sum2(m,m,r) -> m+r; sum2(n,m,r) -> sum2(n+1,m,r+n).  %% tail recursive.   %% third solution, without recursion: don't use recursive function if not necessary sum3(m,m) -> m; sum3(0,m) -> sum3(1,m); sum3(n,m) when n =< m ->  %% don't defensive unless function subject                           %% receive bad argument user intreface     (m*(m+1)-(n-1)*n) div 2. 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -