Search code examples
erlangpass-by-referenceerlang-otperlang-shellerlang-nif

How to use a variable as pass by reference in Erlang?


Why is my output not getting reflected in Lst1?

-module(pmap). 
-export([start/0,test/2]). 

test(Lst1,0) ->
   {ok, [Temp]} = io:fread( "Input the edge weight  ", "~d" ),
   lists:append([Lst1,[Temp]]),
   io:fwrite("~w~n",[Lst1]);

test(Lst1,V) ->
   {ok, [Temp]} = io:fread( "Input the edge weight  ", "~d" ),
   lists:append([Lst1,[Temp]]),
   test(Lst1, V-1).

start() -> 
   {ok, [V]} = io:fread( "Input the number of vertices your graph has  ", "~d" ),
   Lst1 = [],
   test(Lst1,V).

So, my Lst1 is printing [], whereas I expect it to print, suppose, [1,2,3] if I provide input 1,2,3.


Solution

  • You're not using the result of lists:append/2, as @Alexey Romanov correctly pointed out.

    This is how I would fix your code…

    -module(pmap). 
    -export([start/0,test/2]). 
    
    test(Lst1,0) ->
        {ok, [Temp]} = io:fread( "Input the edge weight  ", "~d" ),
        Lst2 = lists:append([Lst1,[Temp]]),
        io:fwrite("~w~n",[Lst2]),
        Lst2;
    test(Lst1,V) ->
        {ok, [Temp]} = io:fread( "Input the edge weight  ", "~d" ),
        Lst2 = lists:append([Lst1,[Temp]]),
        test(Lst2, V-1).
    
    start() -> 
       {ok, [V]} = io:fread( "Input the number of vertices your graph has  ", "~d" ),
       Lst1 = [],
       test(Lst1,V).
    

    But actually, a more idiomatic code to achieve the same result would be…

    -module(pmap). 
    -export([start/0,test/2]). 
    
    test(Lst1,0) ->
        {ok, [Temp]} = io:fread( "Input the edge weight  ", "~d" ),
        Lst2 = lists:reverse([Temp|Lst1]),
        io:fwrite("~w~n",[Lst2]),
        Lst2;
    test(Lst1,V) ->
        {ok, [Temp]} = io:fread( "Input the edge weight  ", "~d" ),
        test([Temp | Lst1], V-1).
    
    start() -> 
       {ok, [V]} = io:fread( "Input the number of vertices your graph has  ", "~d" ),
       Lst1 = [],
       test(Lst1,V).