3 ms·
You really shouldn't be using agent for mutable state. Kind of annoying that the docs push you to that. Agent is most useful when you need to tie the transient
by throwawaymaths 3y ago
You really shouldn't be using agent for mutable state. Kind of annoying that the docs push you to that. Agent is most useful when you need to tie the transient lifetime of some state with something else (think: compilers). Otherwise, it's generally better to use a database, (or ets, if you need performance), GenServer/gen_statem if you need reactive events attached to the state. Agent is just a wrapper over GenServer so it is strictly worse in terms of performance, and honestly, slightly hard to grok as to where actions take place (and thus, who is responsible for failures)
- giraffe_lady 3y agoI love elixir and am very comfortable with functional programming and generally prefer it. But being told you have to write a state machine instead of just += a var is an excellent experience in believing elixir is harder than python.
- sodapopcan 3y agoOf course you example is hyperbole and I certainly understand what you are saying. But the attitude that many programmers take when learning a new language that something is "harder" when it's just different than what they are used to bothers me (to be clear, I'm not directing that at you). But comparing: i = 0 for x in [1, 2, 3, 4]: i += x vs i = Enum.reduce([1, 2, 3, 4], fn x, i -> i + x end) There is nothing inherently "harder" about the functional version, it's just different (and of course comes with its own benefits).
- jcparkyn 3y agoI find that pure functional loops with reduce or fold often get a lot harder to read/write as soon as you have more than one variable to keep track of. Imperative loops don't really have this problem.
- throwawaymaths 3y agoFor me it's the other way around. With reduce you have to explicitly declare what you're keeping between each iteration. When you have an imperative loop the state of any of the variables youve declared is up in the air. It gets even worse if you've shadowed variable names.
- di4na 3y agoEspecially when Enum.sum([1, 2, 3, 4]) Exist ;)
- sodapopcan 3y ago...and Python has sum([1, 2, 3, 4]) so obviously not my point :P ;)
- sarchertech 3y agoIn reality if you’re just trying to += a variable, you’d use reduce (if you couldn’t use one of the built in functions).