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

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.

主站蜘蛛池模板: 浠水县| 永春县| 平度市| 彭水| 遵义县| 灵寿县| 上犹县| 泸水县| 沈阳市| 兴业县| 普兰县| 乌鲁木齐市| 永春县| 龙川县| 怀化市| 金阳县| 伊吾县| 志丹县| 馆陶县| 赣榆县| 乌兰浩特市| 横峰县| 桐乡市| 高平市| 益阳市| 阳江市| 梅河口市| 将乐县| 马鞍山市| 龙海市| 仁布县| 南充市| 普宁市| 高淳县| 延安市| 镇平县| 庄河市| 甘肃省| 商水县| 溧阳市| 辰溪县|