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

mqkwyuun  于 2022-12-08  发布在  Erlang
关注(0)|答案(2)|浏览(181)

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

r9f1avp5

r9f1avp51#

因为Erlang变量是不可变的,根本不能改变。lists:append返回一个新的列表,您可以将其丢弃。

xqnpmsa8

xqnpmsa82#

正如@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).

相关问题