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

如何在Erlang中使用变量作为传递引用?,erlang,pass-by-reference,otp,erlang-shell,erlang-nif,Erlang,Pass By Reference,Otp,Erlang Shell,Erlang Nif,为什么我的输出没有反映在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)

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

因此,我的Lst1正在打印[],而我希望它打印,假设我提供输入1,2,3,[1,2,3],因为Erlang变量是不可变的,根本无法更改
lists:append
返回一个新列表,您将其丢弃。

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

这就是我将如何修复你的代码

-模块(pmap)。
-导出([开始/0,测试/2])。
测试(Lst1,0)->
{ok,[Temp]}=io:fread(“输入边权重”,“~d”),
Lst2=列表:追加([Lst1,[Temp]]),
io:fwrite(“~w~n”,[Lst2]),
Lst2;
测试(Lst1,V)->
{ok,[Temp]}=io:fread(“输入边权重”,“~d”),
Lst2=列表:追加([Lst1,[Temp]]),
试验(Lst2,V-1)。
开始()->
{ok,[V]}=io:fread(“输入图形的顶点数”,“~d”),
Lst1=[],
测试(Lst1,V)。
但实际上,一个更惯用的代码来实现相同的结果将是

-模块(pmap)。
-导出([开始/0,测试/2])。
测试(Lst1,0)->
{ok,[Temp]}=io:fread(“输入边权重”,“~d”),
Lst2=列表:反向([Temp | Lst1]),
io:fwrite(“~w~n”,[Lst2]),
Lst2;
测试(Lst1,V)->
{ok,[Temp]}=io:fread(“输入边权重”,“~d”),
试验([Temp | Lst1],V-1)。
开始()->
{ok,[V]}=io:fread(“输入图形的顶点数”,“~d”),
Lst1=[],
测试(Lst1,V)。

感谢您的评论,实现这一点的备选方案是什么?我对Erlang非常陌生。您的
test
函数应该返回新列表。Brujo Benavides的回答说明了一些方法。