- 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]
.
- Learning Java Functional Programming
- 程序員考試案例梳理、真題透解與強(qiáng)化訓(xùn)練
- Animate CC二維動(dòng)畫設(shè)計(jì)與制作(微課版)
- Full-Stack React Projects
- Unity 5.x By Example
- 深入淺出PostgreSQL
- Hands-On Full Stack Development with Go
- HTML5與CSS3基礎(chǔ)教程(第8版)
- HTML5 APP開(kāi)發(fā)從入門到精通(微課精編版)
- Learning AngularJS for .NET Developers
- Android系統(tǒng)下Java編程詳解
- Practical Predictive Analytics
- Python預(yù)測(cè)分析與機(jī)器學(xué)習(xí)
- Android應(yīng)用程序設(shè)計(jì)
- Enterprise Application Architecture with .NET Core