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

Elixir structure

So far, we haven't seen much more than tiny snippets, demonstrating a fraction of the syntax of Elixir. Now we are going to go into more detail and look at some more in-depth examples.

We will start with what may be considered a functional language's real "hello world", the map function.

Note

Note that this example will use some concepts that we are going to go into more detail in the next few chapters.

The map function essentially takes a function and a list, and applies the function to each element in the list. Ideally, the application of one element in the list does not depend or effect any other application of any other element. Thus, this is usually something that can be trivial (in concept) to parallelize. However, very few languages make it so easy as the functional languages, and in particular, Elixir.

Using what we know now (and some stuff we haven't covered), here's how we might write our own map function:

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..5, square)

Breezing over what we will cover in the next chapter, we have defined a single function, map, which takes in a list and a function, and then recursively applies the provided function to each element in the collection. After the definition, we define another function that squares its input, and we execute our map function with the square function and the list [1, 2, 3, 4, 5].

We should expect the output to be a list where each element is squared.

But from the looks of it, there are two functions! Indeed it may appear to be two, however, this is pattern matching showing itself again. When we invoke a function, the runtime takes the given inputs and attempts to match them against the definition. When the runtime finds the match, it executes the given body.

Here we see the map function, or the first-class citizenry that functions maintain and the clutter-free cruft of boilerplate code given to us by pattern matching.

Next, let's look at the variation of the map function for concurrent programming the parallel map:

defmodule Parallel do
  def pmap(collection, func) do
    collection
    |> Enum.map(&(Task.async(fn -> func.(&1) end)))
    |> Enum.map(&Task.await/1)
  end
end
主站蜘蛛池模板: 安龙县| 彭州市| 秭归县| 兴仁县| 沙湾县| 邵阳市| 沛县| 平定县| 拜城县| 驻马店市| 会昌县| 新津县| 汾阳市| 伊川县| 大港区| 仲巴县| 汶上县| 堆龙德庆县| 梁河县| 分宜县| 延庆县| 瑞丽市| 页游| 宜州市| 邢台市| 崇左市| 石柱| 石家庄市| 永嘉县| 贞丰县| 彩票| 朝阳县| 沐川县| 荃湾区| 广宗县| 阿巴嘎旗| 枣阳市| 昌邑市| 大悟县| 光泽县| 宿州市|