- 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
- Google Flutter Mobile Development Quick Start Guide
- Vue.js前端開發基礎與項目實戰
- Mastering Natural Language Processing with Python
- 實用防銹油配方與制備200例
- Getting Started with CreateJS
- Visual Basic程序設計實驗指導(第4版)
- 你不知道的JavaScript(中卷)
- C程序設計案例教程
- Learning Three.js:The JavaScript 3D Library for WebGL
- Android Wear Projects
- 自學Python:編程基礎、科學計算及數據分析(第2版)
- HTML5+CSS3+JavaScript 從入門到項目實踐(超值版)
- 創意UI Photoshop玩轉移動UI設計
- IBM DB2 9.7 Advanced Application Developer Cookbook
- Java程序設計(項目教學版)