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

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.

主站蜘蛛池模板: 延安市| 都江堰市| 施秉县| 司法| 务川| 花垣县| 高唐县| 册亨县| 泰宁县| 满洲里市| 永胜县| 大同市| 陆川县| 九江市| 普安县| 峨山| 广东省| 大荔县| 聂拉木县| 广平县| 聊城市| 沙洋县| 德庆县| 南投市| 库车县| 天镇县| 丰宁| 岑巩县| 息烽县| 汝南县| 青神县| 砚山县| 郸城县| 河南省| 高密市| 田阳县| 阿坝县| 绿春县| 玉山县| 五家渠市| 崇州市|