3

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.

Manika Sharma
  • 113
  • 1
  • 12

2 Answers2

4

Because Erlang variables are immutable and can't be changed at all. lists:append returns a new list which you throw away.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
3

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).
Brujo Benavides
  • 1,919
  • 12
  • 15