为什么我的输出没有反映在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
的结果。
这就是我将如何修复你的代码…
-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).