Features of functional languages
Most programming languages have the concept of a function. Some languages may call it a subroutine, method, or procedure, but they are essentially the same thing.
Therefore, the person who hears the word “functional language” for the first time is uncomfortable. It sounds like a word for programming languages in general. But that's not the case.
In fact, the term functional language does not have a widely accepted and clear definition. So, by comparing two specific languages, Ruby and Elixir, we will explain (part of) the features of functional languages.
Both Ruby and Elixir handle various data (integer, character string, time, etc.) necessary for program execution by naming them. This name is called variable. As an example, let's consider the process of adding
"!" to the end of the string pointed to by variable
s when its length is 3 or less.
s points to the string
"abc". This string is stored in a memory location. In Ruby, this data can be altered directly to
"abc!". However, Elixir cannot alter the data itself. Instead, it transforms the data to another data. Specifically,
"!" are concatenated to create the string
"abc!", and it is again associated with the variable
Although it looks like a minor difference, it actually has a decisive meaning. What happens if two programs
Y are running in parallel on the same computer, both have variable
s that refers to the string
"abc" stored in the same location in the memory, and the above process is executed almost simultaneously on both programs?
In the case of Ruby, something bad happens depending on the timing. Immediately after
X confirms that the length of the string pointed to by variable
s is 3, if
"!" to the same string,
X also adds
"!" after that, so finally thestring pointed to by variable
s will be changed to
But this doesn't happen with Elixir. This is because the original data is kept intact and another data is newly created. In other words, Elixir transforms data without changing it.
Thus, there is a significant difference between alteration and transformation. The biggest feature of the functional language Elixir is that data cannot be altered. Programs written in Elixir proceed through a chain of data transformations. Languages like Elixir are called functional because this data transformation is similar to a mathematical function.
Of course, if you program carefully in Ruby, the above problems will not occur. But humans make mistakes. Elixir is safer in situations where parallel processing is involved.