- Learning Elixir
- Kenny Ballou
- 391字
- 2021-07-23 14:47:54
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
- Visual Basic .NET程序設計(第3版)
- Android應用程序開發與典型案例
- C語言程序設計(第2 版)
- 深入淺出Prometheus:原理、應用、源碼與拓展詳解
- FreeSWITCH 1.6 Cookbook
- Mastering KnockoutJS
- 學Python也可以這么有趣
- PySpark Cookbook
- Advanced Express Web Application Development
- Kubernetes源碼剖析
- HTML5開發精要與實例詳解
- FFmpeg開發實戰:從零基礎到短視頻上線
- R語言實戰(第2版)
- 威脅建模:設計和交付更安全的軟件
- 面向WebAssembly編程:應用開發方法與實踐