- Learning Elixir
- Kenny Ballou
- 331字
- 2021-07-23 14:47:54
Elixir files
Elixir uses two files, .ex
for compiled code and .exs
for scripts. They must both be UTF-8 encoded. We will go over .ex
some more when we introduce mix in the next chapter. But for now, let's discuss .exs
a little more.
We can write all the Elixir code we have shown so far into a script (we won't though, there is just a small subset) and then we can use the interactive interpreter to load up our script and run it.
For example, we can put the MyMap
code from earlier into a script:
defmodule MyMap do def map([], _) do [] end def map([h|t], f) do [f.(h) | map(t, f)] end end square = fn x -> x * x end MyMap.map([1, 2, 3, 4, 5], square)
Go ahead and save it as mymap.exs
. Launch a terminal and use the cd
command to navigate to the directory that you saved your script in and then launch iex
.
Once in iex
, we will use import_file/1
to import and launch our script.
In your iex
, type h(import_file/1)
to get the documentation of import_file/1
:
iex(1)> h(import_file/1) defmacro import_file(path) Evaluates the contents of the file at path as if it were directly typed into the shell. path has to be a literal binary. A leading ~ in path is automatically expanded. Examples # ~/file.exs value = 13 # in the shell iex(1)> import_file "~/file.exs" 13 iex(2)> value 13
Loading our code, we should see something similar to the following:
iex(1)> import_file("mymap.exs") [1, 4, 9, 16, 25]
Furthermore, we have access to the MyMap.map/2
and square/1
functions we defined in the script. We can now use these in the interactive session to debug or explore the given code:
iex(2)> double = fn x -> x * 2 end #Function<6.90072148/1 in :erl_eval.expr/5> iex(3)> MyMap.map([1, 2, 3, 4, 5], double) [2, 4, 6, 8, 10]
Here, instead of squaring the number, we double it, and we operate over the same list, [1, 2, 3, 4, 5]
.
- Web應用系統開發實踐(C#)
- Hyper-V 2016 Best Practices
- Python爬蟲開發:從入門到實戰(微課版)
- Web Application Development with R Using Shiny(Second Edition)
- Java Web基礎與實例教程
- 零基礎學Python網絡爬蟲案例實戰全流程詳解(高級進階篇)
- Python機器學習基礎教程
- Oracle 18c 必須掌握的新特性:管理與實戰
- Learning SciPy for Numerical and Scientific Computing(Second Edition)
- 基于ARM Cortex-M4F內核的MSP432 MCU開發實踐
- R數據科學實戰:工具詳解與案例分析
- Python從入門到精通(第3版)
- IDA Pro權威指南(第2版)
- STM8實戰
- 官方 Scratch 3.0 編程趣味卡:讓孩子們愛上編程(全彩)