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

Rob Charlton <>
Thu Oct 15 13:16:45 CEST 2009


sapan shah wrote:
> So, the basic question is: If the test/2 function is side effect free (no
> put, no get or no io:format..), would erlang evaluater still call the test/2
> function again, if it had called the same fuction with same arguments
> erlier???
>   
Try this code and see:

-module(side_effect_test).

-compile(export_all).

-include_lib("stdlib/include/ms_transform.hrl").
test() ->
    dbg:tracer(),
    dbg:p(all,call),
    dbg:tpl(?MODULE,dbg:fun2ms(fun(_)->return_trace() end)),
    %% and now the test
    test2(side_effect_free(2,2),side_effect_free(2,2)).

test2(A,B) ->
    ok.

side_effect_free(A,B) ->
    A + B.

And the output:
1> side_effect_test:test().
(<0.31.0>) call side_effect_test:side_effect_free(2,2)
(<0.31.0>) returned from side_effect_test:side_effect_free/2 -> 4
(<0.31.0>) call side_effect_test:side_effect_free(2,2)
(<0.31.0>) returned from side_effect_test:side_effect_free/2 -> 4
(<0.31.0>) call side_effect_test:test2(4,4)
(<0.31.0>) returned from side_effect_test:test2/2 -> ok

So the answer is no - Erlang doesn't know that "side_effect_free" is
free of side effects and that multiple calls with the same parameters
can be optimized away, and so will evaluate it twice.

Cheers

Rob

-- 
Erlang Training and Consulting Ltd
www.erlang-consulting.com



More information about the erlang-questions mailing list