Erlang:正确地将数据存储在记录中并检索它?

时间:2013-03-26 22:50:19

标签: erlang record

我使用输出

运行以下代码
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> 

我想知道的是如何将值正确存储到记录中,显然record_io:print().的输出应该是99而不是2。这是代码。

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

我尝试了另一种方式,但也没有用。

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> 

修改后的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]).

编辑:解决方案。

代码

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

命令行。

Rec = record_io:store(99).
record_io:print(Rec).
stored: 99
{memory,99}
stored: 99
ok

1 个答案:

答案 0 :(得分:1)

您无法修改Erlang中的记录。只创造新的。见How do I modify a record in erlang?