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

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

主站蜘蛛池模板: 上林县| 新乐市| 韶关市| 玉屏| 咸阳市| 龙山县| 山西省| 乐昌市| 壶关县| 岳阳市| 天全县| 寿阳县| 新津县| 庆安县| 洪雅县| 沙湾县| 商都县| 丰顺县| 资中县| 基隆市| 池州市| 青州市| 龙州县| 中西区| 阿克苏市| 尼玛县| 三原县| 亚东县| 柳州市| 揭东县| 上饶县| 凤城市| 唐山市| 海兴县| 阿拉善盟| 赤城县| 云龙县| 重庆市| 浠水县| 大同市| 呼伦贝尔市|