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

  • Mastering Elixir
  • André Albuquerque Daniel Caixinha
  • 409字
  • 2021-08-05 10:42:46

MapSets

If you're looking for an implementation of a set in Elixir, you're looking for MapSet. You create and manipulate them with the functions from the MapSet module. Here are some examples:

iex> set = MapSet.new
#MapSet<[]>
iex> set = MapSet.put(set, 1)
#MapSet<[1]>
iex> set = MapSet.put(set, 2)
#MapSet<[1, 2]>
iex> set = MapSet.put(set, 1)
#MapSet<[1, 2]>

Sets, by definition, can't contain duplicates. So, inserting a value that's already there has no effect. You can find the documentation for the MapSet module at https://hexdocs.pm/elixir/MapSet.html.

There are three types, related to the underlying Erlang VM, that we have to mention before closing this section. They are as following:

  • Reference: A reference is a type created by the Kernel.make_ref function. This functions creates an almost-unique reference, which gets repeated around every 282 calls. We will not use references in this book.
  • Port: A port is a reference to a resource. The Erlang VM uses it to interact with external resources, such as an operating system process. We will talk a bit more about ports later in this chapter, when we discuss the interoperability between Elixir and Erlang.
  • PID: A PID is the type used to identify processes in the Erlang VM. You'll see PIDs in action later in this book, when we start working with Erlang VM processes.

To complete this section, there's a function that we want to highlight: the i function, which is auto-imported from the Kernel module. You can use it to find out more information about a data type. It will print information about the data type of the term you pass as an argument. Here is an example with a string:

iex> i("a string")
Term
"a string"
Data type
BitString
Byte size
8
Description
This is a string: a UTF-8 encoded binary. It's printed surrounded by
"double quotes" because all UTF-8 encoded codepoints in it are printable.
Raw representation
<<97, 32, 115, 116, 114, 105, 110, 103>>
Reference modules
String, :binary
Implemented protocols
IEx.Info, Collectable, List.Chars, String.Chars, Inspect

And, with this, we've finished our tour of the data types in Elixir! We didn't go into much detail, but with the links we left throughout this section, you'll see how incredible the documentation in Elixir is, and how easy it is to figure out what a certain function does or the purpose of a certain argument.

We will now jump into one of the most prominent features of Elixir (and also one that will definitely change how you write programs): pattern matching.

主站蜘蛛池模板: 三亚市| 平度市| 航空| 蛟河市| 迁西县| 佛山市| 家居| 武功县| 栖霞市| 万载县| 涞水县| 志丹县| 遂宁市| 满城县| 高青县| 元谋县| 阜新市| 谷城县| 甘孜| 分宜县| 华蓥市| 古交市| 南川市| 西盟| 平陆县| 沅江市| 久治县| 缙云县| 米易县| 古丈县| 延寿县| 大关县| 隆安县| 阜平县| 九龙坡区| 万山特区| 桃源县| 昆山市| 廊坊市| 吉水县| 长治县|