PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

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

 July 06, 2022     erlang, erlang-nif, erlang-otp, erlang-shell, pass-by-reference     No comments   

Issue

Why is my output not getting reflected in 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).

So, my Lst1 is printing [], whereas I expect it to print, suppose, [1,2,3] if I provide input 1,2,3.


Solution

You're not using the result of lists:append/2, as @Alexey Romanov correctly pointed out.

This is how I would fix your code…

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

But actually, a more idiomatic code to achieve the same result would be…

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


Answered By - Brujo Benavides
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,207,470

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing