Single purpose

I am currently trying to master Erlang. This is the first functional programming language that I look at, and I noticed that in Erlang, every assignment you perform is one assignment. And, apparently, not only in Erlang, but also in many other functional programming languages, tasks are performed using a single assignment.

I'm really confused about why they did it. What is the purpose of a single purpose? What benefits can we get from him?

+7
source share
3 answers

Immutability (what you call a single assignment) simplifies many things because it extracts the time variable from your programs.

For example, in math, if you say

x = y 

You can replace x with y , everywhere. In operating programming languages, you cannot guarantee that this equality holds: there is a β€œtime” (state) associated with each line of code. This time also leaves the door open for unwanted side effects which is the number one opponent of modularity and concurrency.

For more information, see this: http://mitpress.mit.edu/sicp/full-text/book/book-ZH-20.html#%_sec_3.1.1

+9
source

Due to Single Assignment , side effects are so minimal. Infact, it's so hard to write code with race conditions or any side effects in Erlang. This is due to the fact that the compiler easily reports unused variables, created terms that are not used, shaded variables (especially inside funs ), etc.

Another advantage Erlang has received in this is: Link transparency . A function in Erlang will depend only on the variables passed to it and NOT on global variables, except for MACROS (and macros cannot be changed at run time, they are constants.). Finally, if you watched the Erlang Movie , the Sophisticated Error Detection Mechanism that was built into Erlang depends on Erlang assigning variables to Once.

+3
source

The presence of variables that store their values ​​greatly facilitates the understanding and debugging of code. With simultaneous processes, you still get the same problems, so in any case there are enough complications, without any variable potentially changing its value at any time. Think of it as encapsulating side effects, only allowing them when they are explicit.

+2
source

All Articles