h 是 Elixir shell 中最有用的工具了. 多亏了这门语言对文档的支持一级棒, 我们可以用这个辅助函数查看任意代码的文档. 我们看一下使用的例子:
iex> h Enum
Enum
Provides a set of algorithms that enumerate over enumerables according to the
Enumerable protocol.
┃ iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)
┃ [2, 4, 6]
Some particular types, like maps, yield a specific format on enumeration. For
example, the argument is always a {key, value} tuple for maps:
┃ iex> map = %{a: 1, b: 2}
┃ iex> Enum.map(map, fn {k, v} -> {k, v * 2} end)
┃ [a: 2, b: 4]
Note that the functions in the Enum module are eager: they always start the
enumeration of the given enumerable. The Stream module allows lazy enumeration
of enumerables and provides infinite streams.
Since the majority of the functions in Enum enumerate the whole enumerable and
return a list as result, infinite streams need to be carefully used with such
functions, as they can potentially run forever. For example:
┃ Enum.each Stream.cycle([1, 2, 3]), &IO.puts(&1)
甚至可以在 shell 中与补全功能组合在一起使用. 假想一下这是我们第一次使用 Map:
iex> h Map
Map
A set of functions for working with maps.
Maps are key-value stores where keys can be any value and are compared using
the match operator (===). Maps can be created with the %{} special form defined
in the Kernel.SpecialForms module.
iex> Map.
delete/2 drop/2 equal?/2
fetch!/2 fetch/2 from_struct/1
get/2 get/3 get_and_update!/3
get_and_update/3 get_lazy/3 has_key?/2
keys/1 merge/2 merge/3
new/0 new/1 new/2
pop/2 pop/3 pop_lazy/3
put/3 put_new/3 put_new_lazy/3
split/2 take/2 to_list/1
update!/3 update/4 values/1
iex> h Map.merge/2
def merge(map1, map2)
Merges two maps into one.
All keys in map2 will be added to map1, overriding any existing one.
If you have a struct and you would like to merge a set of keys into the struct,
do not use this function, as it would merge all keys on the right side into the
struct, even if the key is not part of the struct. Instead, use
Kernel.struct/2.
Examples
┃ iex> Map.merge(%{a: 1, b: 2}, %{a: 3, d: 4})
┃ %{a: 3, b: 2, d: 4}
如我们所见, 不仅可以看到模块中有什么函数还能看到每个单独函数的文档, 而且它们大多都有使用示例.
i
让我们用刚才学到的 h 来 了解一下 i 辅助函数:
iex> h i
def i(term)
Prints information about the given data type.
iex> i Map
Term
Map
Data type
Atom
Module bytecode
/usr/local/Cellar/elixir/1.3.3/bin/../lib/elixir/ebin/Elixir.Map.beam
Source
/private/tmp/elixir-20160918-33925-1ki46ng/elixir-1.3.3/lib/elixir/lib/map.ex
Version
[9651177287794427227743899018880159024]
Compile time
no value found
Compile options
[:debug_info]
Description
Use h(Map) to access its documentation.
Call Map.module_info() to access metadata.
Raw representation
:"Elixir.Map"
Reference modules
Module, Atom