[erlang-questions] Calling a Function with Same argument twice

David Mercer <>
Wed Oct 14 15:52:42 CEST 2009


sapan shah wrote:

> test(X,Y) ->
>     {element(1,test(X-1,Y-1)),element(2,test(X-1,Y-1))}.
. . .
> Here, when start(1) is called, it intern calls
> {element(1, test(1,1), element(2, test(1,1)}
> 
> The first call of test(1,1) should recursively evaluate test(1,1) while
> the
> second call should already use the value returned by the first call.. Is
> this a right thinking???

No, test(X,Y) is evaluating test(X-1,Y-1) twice.  If you wanted it to only
evaluate it once, you could write:

	test(X,Y) ->
		Test = test(X-1,Y-1),
		{element(1,Test), element(2,Test)}

Even in Haskell, you would have to evaluate test(X-1,Y-1) twice, since there
are side-effects (the put call in test(0,0)), which would require it to be
wrapped in a monad.  (I'm not a Haskell expert, never having written a line
of it in my life, so feel free to correct me if my understanding of the
language is wrong.)

Cheers,

David

> -----Original Message-----
> From:  [mailto:] On
> Behalf Of sapan shah
> Sent: Wednesday, October 14, 2009 8:09 AM
> To: erlang-questions
> Subject: [erlang-questions] Calling a Function with Same argument twice
> 
> Hi,
> 
> see the code below.
> %%%%%%%%%%
> -module(temp).
> -compile(export_all).
> 
> 
> start(X) ->
>     put(test, 0),
>     case X of 1 -> test(2, 2); 2-> test1(2) end,
>     get(test).
> 
> 
> test(0,0) ->
>     put(test, get(test) +1),
>     {0,0};
> 
> test(X,Y) ->
>     {element(1,test(X-1,Y-1)),element(2,test(X-1,Y-1))}.
> 
> 
> test1(0) ->
>     put(test, get(test) +1),
>     {0};
> test1(X) ->
>     {element(1,test1(X-1))}.
> %%%%%%%
> 
> We call temp:start(1), the output is 4. The output should have been 1.
> Here, when start(1) is called, it intern calls
> {element(1, test(1,1), element(2, test(1,1)}
> 
> The first call of test(1,1) should recursively evaluate test(1,1) while
> the
> second call should already use the value returned by the first call.. Is
> this a right thinking???
> --
> Regards,
> Sapan Shah



More information about the erlang-questions mailing list