- 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]
.
- PHP 7底層設計與源碼實現
- C++ Builder 6.0下OpenGL編程技術
- 無代碼編程:用云表搭建企業數字化管理平臺
- C#程序設計(慕課版)
- The Computer Vision Workshop
- GeoServer Beginner's Guide(Second Edition)
- FFmpeg入門詳解:音視頻原理及應用
- C語言程序設計同步訓練與上機指導(第三版)
- 大數據分析與應用實戰:統計機器學習之數據導向編程
- Learning OpenCV 3 Computer Vision with Python(Second Edition)
- CoffeeScript Application Development Cookbook
- UML2面向對象分析與設計(第2版)
- C++ System Programming Cookbook
- Google Adsense優化實戰
- Spring Microservices