Thomaz Leite
Parte 2
Extensibilidade
Produtividade
Compatibilidade
Processes
Modules
Data/Type
defprotocol Size do
@doc "Calculates the size of a data structure"
def size(data)
end
defimpl Size, for: BitString do
def size(string), do: byte_size(string)
end
defimpl Size, for: Map do
def size(map), do: map_size(map)
end
defimpl Size, for: Tuple do
def size(tuple), do: tuple_size(tuple)
end
iex> Size.size("foo")
3
iex> Size.size({:ok, "hello"})
2
iex> Size.size(%{label: "some label"})
1
defmodule User do
defstruct [:name, :age]
end
defimpl Size, for: User do
def size(_user), do: 2
end
Abstract Syntax Tree
iex> quote do: sum(1, 2, 3)
{:sum, [], [1, 2, 3]}
iex> number = 13
iex> Macro.to_string(quote do: 11 + number)
"11 + number"
iex> number = 13
iex> Macro.to_string(quote do: 11 + unquote(number))
"11 + 13"
defmacro unless(clause, do: expression) do
quote do
if(!unquote(clause), do: unquote(expression))
end
end
$ mix new foo
$ cd foo
$ mix test
$ mix hex.publish
$ mix hex.docs
defmodule KVServer.Command do
@doc ~S"""
Parses the given `line` into a command.
## Examples
iex> KVServer.Command.parse "CREATE shopping\r\n"
{:ok, {:create, "shopping"}}
"""
def parse(_line) do
:not_implemented
end
end
1> inet_res:lookup("erlang.com", in, mx).
[{20,"mail.erlang.com"}]
iex(1)> :inet_res.lookup('erlang.com', :in, :mx)
[{20, 'mail.erlang.com'}]