[erlang-questions] [Fwd: Re: Functional Programming]

Zac Brown zac@REDACTED
Wed Aug 29 23:56:08 CEST 2007


Hi:

    You're correct that it is recursion and the calls you listed are
corrected. Essentially this is a stack-expanding recursive call which
are bad because you're building up your recursive calls and if its a big
number, you risk blowing the stack. The best way to define this function
in the manner you have is as follows:

fac(N) - > fac_helper(N, 1).

fac_helper(1, Tot) -> Tot;
fac_helper(N, Tot) ->
    fac_helper(N - 1, Tot * N).

We keep track of the current sum with the variable Tot, which means that
we don't build the stack, we call in place because we don't rely on
later function calls in order to get our answer, we only rely on a
variable that keeps track of your current total. This is called tail
recursion and is the best way to write recursive functions.

Cheers,
Zac

Lone Wolf wrote:
> Hi.
> Consider please this Erlang code:
>  
> code:
> ------------------------------------------------------------------------
>
>
>     fac(1) ->
>       1;
>     fac(N) ->
>       N * fac(N - 1).
>
>     ------------------------------------------------------------------------
>
>
> I don't understand whats happening when I call:
> fac(5)
> I'm not sure but it seems to me it is "Recursion", right?
> 5 * fac(4)
> 4 * fac(3)
> 3 * fac(2)
> etc..
> Thanks.
>
>
> */Deep into that darkness peering, long I stood there, wondering,
> fearing, Doubting, dreaming dreams no mortal ever dreamed before./*
> */E.A Poe/*
> *//*
> *//* 
>
> ------------------------------------------------------------------------
> Boardwalk for $500? In 2007? Ha!
> Play Monopoly Here and Now
> <http://us.rd.yahoo.com/evt=48223/*http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow>
> (it's updated for today's economy) at Yahoo! Games.
> ------------------------------------------------------------------------
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions






More information about the erlang-questions mailing list