Reputation: 5585
I ran the following code with the output
Erlang R16B (erts-5.10.1) [smp:8:8] [async-threads:10]
Eshell V5.10.1 (abort with ^G)
1> rr(record_io).
[memory]
2> record_io:store(99).
stored: 2
ok
3> record_io:print().
stored: 2
ok
4>
What I wanted to know is how to do I properly store a value into a record, obviously the output for record_io:print().
should have been 99
and not 2
. Heres the code.
-module(record_io).
-export([store/1, print/0]).
-record(memory, {value}).
store(Value) ->
#memory{ value = Value},
io:format("stored: ~p~n",[#memory.value]).
print() ->
io:format("stored: ~p~n",[#memory.value]).
I tried this another way and that too didn't work.
4> c(record_io).
record_io.erl:6: Warning: a term is constructed, but never used
{ok,record_io}
5> rr(record_io).
[memory]
6> record_io:store(S,10).
* 1: variable 'S' is unbound
7>
The code for the modified record_io.
-module(record_io).
-export([store/2, print/1]).
-record(memory, {value}).
store(S,Value) ->
S#memory{ value = Value},
io:format("stored: ~p~n",[S#memory.value]),
S.
print(S) ->
io:format("stored: ~p~n",[S#memory.value]).
EDIT: Solution.
The code
-module(record_io).
-export([store/1, print/1]).
-record(memory, {value}).
store(Value) ->
Rec2 = #memory{ value = Value},
io:format("stored: ~p~n",[Rec2#memory.value]),
Rec2.
print(S) ->
io:format("stored: ~p~n",[S#memory.value]).
The command line.
Rec = record_io:store(99).
record_io:print(Rec).
stored: 99
{memory,99}
stored: 99
ok
Upvotes: 0
Views: 777
Reputation: 18473
You cannot modify records in Erlang. Only creating new ones. see How do I modify a record in erlang?
Upvotes: 1