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

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].

主站蜘蛛池模板: 上杭县| 确山县| 永安市| 时尚| 垫江县| 利津县| 黄陵县| 斗六市| 昌图县| 南漳县| 贵溪市| 白山市| 乌什县| 宁国市| 广平县| 霍林郭勒市| 驻马店市| 五大连池市| 澄江县| 永顺县| 赞皇县| 佛冈县| 石屏县| 公主岭市| 顺平县| 丹阳市| 九江市| 万宁市| 新丰县| 高要市| 上思县| 临沭县| 齐齐哈尔市| 汤原县| 彩票| 重庆市| 安义县| 军事| 泸溪县| 宜兰县| 明水县|