Search code examples
erlangrecorderl

Modifying an Erlang Record


I know that a record in Erlang cannot be changed once it has been set. I am attempting to use a record to increase a value.

add_new_num() ->
    Number = random:uniform(6),
    STR = #adder{value = 7},
    New = add(STR, Number).         

add(#adder{value =V} = Adder, Value) ->
    Adder#adder{value = V + Value}.

When running add_new_num() I will always get 7 + Number. This is not what I want. I want to get it to do the following.

add_new_num() -> 7 + Number = Val
add_new_num() -> Val + Number = Val2
add_new_num() -> Val2 + Number = Val3
...

How can I achieve this?


Solution

  • There are various ways to do this. Think about where you want to store the value: Erlang doesn't have "static variables" like C, so the function itself cannot remember the value.

    You could pass the current record as an argument to add_new_num, and get the updated record from its return value. You could keep a process running, and send messages to query it for the current value and to ask it to increase the value. Or you could store the value in an ETS table, or even Mnesia.