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

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
主站蜘蛛池模板: 贡觉县| 双辽市| 永年县| 唐山市| 南平市| 文山县| 佛学| 东山县| 资源县| 台东县| 唐山市| SHOW| 临夏市| 武功县| 宜兰市| 新沂市| 民县| 土默特右旗| 兴化市| 仪陇县| 池州市| 额尔古纳市| 阿合奇县| 南阳市| 昌宁县| 二连浩特市| 朝阳县| 鸡泽县| 阳江市| 依兰县| 交口县| 宁津县| 封开县| 宣城市| 秭归县| 大冶市| 合肥市| 紫云| 乌苏市| 柞水县| 遵义县|