2 ms·
A couple of ways: Function parameters with a "state" structure, processes (and function parameters). A common pattern is something like this: loop(N) ->
by Jtsummers 5y ago
A couple of ways: Function parameters with a "state" structure, processes (and function parameters).
A common pattern is something like this:
loop(N) ->
Next = do_stuff(N,...),
loop(Next).
That would be the first pattern. So you could have a state variable (or set of variables) which are changed on the next iteration. Since Erlang does tail call elimination, this is the same as a while/for loop in other languages but does not have explicit mutation. You can also return the new state and thread it through various function calls.
With processes, you can do something similar:
counter(N) ->
receive
Pid -> Pid ! N,
end,
counter(N+1).
user(Count_PID) ->
Counter_PID ! self(),
receive
N -> io:format("~p times~n", [N])
end,
user(Counter_PID).
(probably typos above, haven't done Erlang in a while)
Between these two, and more advanced use of language modules, you can provide mutable state (of a sort).
EDIT: Also worth noting that, before getting to anything beyond the basic syntax, both records and maps permit updates rather cleanly. For instance, with a map you might have:
Map = #{a => 10}
Updated = Map#{a := 42}
So if you have a register map and do something like (again, been a while so forgive syntax errors):
update_register(Rs, Register, Value) ->
Rs#{ Register := Value }.
The rest of the map is left unaltered, only the bit that needs to be updated gets changed. And Erlang/BEAM is careful about not making more copies than needed so in theory (at one point I studied these details, I've forgotten the specifics) this should result in very little new memory being allocated for the updated map.