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

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
主站蜘蛛池模板: 嘉义县| 新化县| 时尚| 正镶白旗| 葫芦岛市| 鄂温| 巴彦淖尔市| 阳西县| 洪湖市| 大方县| 夏邑县| 睢宁县| 琼海市| 措勤县| 嘉峪关市| 永德县| 武定县| 六安市| 海淀区| 江门市| 嘉定区| 嘉黎县| 江阴市| 特克斯县| 绵阳市| 从江县| 祁门县| 玉树县| 安乡县| 兴海县| 汽车| 万全县| 阜宁县| 涡阳县| 延寿县| 凌源市| 兖州市| 诸城市| 万山特区| 安溪县| 石河子市|