如何在 Erlang 中使用变量作为引用传递?

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

为什么我的输出没有反映在 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).

因此,如果我提供输入 1,2,3,我的 Lst1 正在打印 [],而我希望它打印 [1,2,3]。

因为Erlang变量是不可变的,根本不能改变。 lists:append returns 您丢弃的新列表。

正如@Alexey Romanov 正确指出的那样,您没有使用 lists:append/2 的结果。

这就是我修复你的代码的方法…

-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).

但实际上,实现相同结果的更惯用代码是……

-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).