- Mastering Elixir
- André Albuquerque Daniel Caixinha
- 247字
- 2021-08-05 10:42:46
Keyword lists
A keyword list is a list in which its elements have a specific format: they are tuples where the first element is an atom (the second element can be of any type), as demonstrated in the following example:
iex> [name: "Gabriel", age: 1] = [{:name, "Gabriel"}, {:age, 1}]
[name: "Gabriel", age: 1]
We can create keyword lists using the following syntax:
iex> keyword_list = [name: "Gabriel", age: 1]
[name: "Gabriel", age: 1]
iex> keyword_list[:name]
"Gabriel"
As you can see from the previous snippet, a keyword list is indeed a list of tuples, with an atom; you can access values in a keyword list using the same syntax as you would in maps. As an alternative, you can use the get function from the Keyword module. Note that this way of declaring a keyword list is just syntatic sugar, as internally this still is a list of tuples–which means that searching for an item in a keyword list is O(n), and not O(1) as in maps.
In a keyword list, contrary to what happens in maps, you can have more than one value for a given key. Also, you can control the order of its elements. Usually, keyword lists are used to allow functions to receive an arbitrary number of optional arguments. We'll be showing an example of this when we look at named functions later in this chapter. You can find all the operations you can do on a keyword list at https://hexdocs.pm/elixir/Keyword.html.
- Raspberry Pi for Python Programmers Cookbook(Second Edition)
- Java入門經典(第6版)
- 算法零基礎一本通(Python版)
- Java完全自學教程
- Rake Task Management Essentials
- Visual Basic程序設計教程
- Spring Boot+Spring Cloud+Vue+Element項目實戰:手把手教你開發權限管理系統
- 基于Java技術的Web應用開發
- 從0到1:HTML+CSS快速上手
- Java Web程序設計任務教程
- Python之光:Python編程入門與實戰
- Illustrator CC平面設計實戰從入門到精通(視頻自學全彩版)
- 深入解析Java編譯器:源碼剖析與實例詳解
- PHP+MySQL動態網站開發從入門到精通(視頻教學版)
- Hands-On Robotics Programming with C++