- Learning Elixir
- Kenny Ballou
- 420字
- 2021-07-23 14:47:53
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.
- 多媒體CAI課件設(shè)計與制作導(dǎo)論(第二版)
- VMware View Security Essentials
- Microsoft Exchange Server PowerShell Cookbook(Third Edition)
- Azure IoT Development Cookbook
- 小創(chuàng)客玩轉(zhuǎn)圖形化編程
- 技術(shù)領(lǐng)導(dǎo)力:程序員如何才能帶團(tuán)隊
- Scratch 3.0少兒編程與邏輯思維訓(xùn)練
- Drupal 8 Module Development
- Linux:Embedded Development
- 圖數(shù)據(jù)庫實戰(zhàn)
- C語言從入門到精通
- C#程序設(shè)計(項目教學(xué)版)
- 軟件項目管理實用教程
- Android嵌入式系統(tǒng)程序開發(fā):基于Cortex-A8(第2版)
- Software-Defined Networking with OpenFlow(Second Edition)