3

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

4

2 回答 2

4

因为 Erlang 变量是不可变的,根本无法更改。lists:append返回一个你扔掉的新列表。

于 2020-11-07T15:44:13.953 回答
3

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

这就是我将如何修复您的代码...</p>

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

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

-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).
于 2020-11-07T18:20:16.990 回答