官术网_书友最值得收藏!

Everything is an expression

We have hinted at this concept in the previous chapter, but let's discuss it in more detail here.

In Elixir, there are no statements. Everything is an expression. Let's break this down. Statements typically refer to instructions where the programmer specifies to the computer or runtime to perform some action. This action could, for example, add two numbers together and assign the value to a variable. Or, it could instruct the machine to print data—strings, numbers, and bits—to the console. Or, it could instruct the machine to make a remote connection to another machine and request a web page. These actions may have ephemeral results—the value of the variable, output text on the screen, and page data from the request. But in all of these examples, the code, itself, which instructs the performance of such actions, does not necessarily, nor inherently return anything.

To contrast this to expressions, we note that we can still do all of these things, however, each instruction will return something. When we add two numbers and then binding the result to a variable, we still get the value. When we send data to the console, we see a sort of success confirmation symbol. When we request the data from remote connection, we would likely get a success or failure symbol and the response body or the reason for failure, respectively.

More concretely, note that when we add two numbers and assign the value, we still get the result printed:

iex(1)> a = 4 + 2
6

When we use IO.puts/1 to print data to the console, we see the :ok symbol:

iex(2)> IO.puts(a)
6
:ok

We'll wait to see the last example, but we can see the idea.

Why does this distinction matter? Are we not accomplishing the same things, regardless of whether a line in the program is a statement or an expression? Yes, we are accomplishing the same things, just with different approaches. However, we gain some distinct advantages if everything is an expression, namely, in terms of composability. That is, with expressions, the concept of program flow and execution becomes more evident because we can compose parts of our programs in a way that is more readable and natural.

Of course, we can write Elixir code, similarly to the way we have written imperative code in the past. However, this will eventually be more painful than to do it the functional way.

We will see this materialize more as our journey progresses.

主站蜘蛛池模板: 香港| 黔东| 历史| 九江县| 高碑店市| 华宁县| 巩留县| 共和县| 岳阳市| 集安市| 肥乡县| 贵州省| 婺源县| 新河县| 平顺县| 开封县| 资阳市| 南开区| 沈丘县| 安溪县| 安福县| 饶平县| 张家口市| 义乌市| 临沧市| 三都| 赤城县| 东乌珠穆沁旗| 东源县| 印江| 西城区| 巢湖市| 平江县| 建始县| 九龙县| 汶上县| 沙洋县| 益阳市| 清丰县| 辽宁省| 芮城县|