Pato
Pato

Reputation: 11

Erlang/ variable assignment

I looked into Erlang and was puzzled that reassignment of Variables, e.g. Counter is possible:

loop(Value,Counter)-> io:format("~s,~n",[Value]), loop(Value,Counter-1).

I expected to see a purely functional language. Or, should I shift my POV?

Cheers,

Tomas

Upvotes: 0

Views: 575

Answers (2)

didierc
didierc

Reputation: 14730

loop(Value,Counter)-> io:format("~s,~n",[Value]), loop(Value,Counter-1).

In the above function definition, the name of the function itself appears on the right hand side of the definition, and is used with the same arity. We call this type of definition a recursive definition. Each recursive call will define a value called Counter which is only visible within the current recursion level. In other words, the number corresponding to the evaluation of the expression Counter - 1 will be bound to a new Counter variable, unrelated scope-wise to the one used in the expression.

However, this type of recursive function call is called tail-recursive. It's a specific type of call which carries the property of being optimizable to a real loop. The end result is that the memory cell for Counter used by the function will be updated with the new value and used in the recursive call, rather than allocated again for that new Counter value(1). This allow potentially infinite recursion schemes.


Regarding the notion of functional language, it is difficult to answer that without establishing first a proper definition of what constitute a functional language, and what purely functional means.

In my book, an functional language is a language based of lambda calculus concepts: function abstraction and application, higher order functions: this is also called functions as first class citizen of the language. Erlang definitely fits that model. A pure FL would probably be one not supporting the other main paradigm of programmation, namely imperative (variable mutability). Again Erlang matches that very definition. If you have different definitions, then Erlang's situation might be different.

Pascal pointed out in the comments section that there's a facility in Erlang which doesn't follow the pure functional language paradigm: Process dictionaries. Indeed it is possible to set values in that structure, and as noted:

Note that using the Process Dictionary:

  • Destroys referencial transparency

  • Makes debugging difficult

  • Survives Catch/Throw

(emphasis mine).

Hence, Erlang isn't strictly pure.


(1) tail recursion isn't the only way to get that optimization in place: see http://learnyousomeerlang.com/recursion

Upvotes: 3

Danil Onishchenko
Danil Onishchenko

Reputation: 2040

  1. There is no reassignment in your example - Counter-1 is a new value which is not assigned to any existing variable.
  2. Erlang isn't a pure functional language.

Upvotes: 4

Related Questions