String.split/1 返回 list - Elixir 的基本数据结构之一,以及 maps 和 tuples。列表是您在 Elixir 中的首选基本集合。即使在内部它是linked list,您也可以使用Enum module 中的函数对其执行各种操作:
$ iex
iex(1)> ls = String.split("Hello World from the hell")
["Hello", "World", "from", "the", "hell"]
iex(2)> i ls
Term
["Hello", "World", "from", "the", "hell"]
Data type
List
Reference modules
List
iex(3)> Enum.take(ls, 2)
["Hello", "World"]
iex(4)> Enum.at(ls, 4)
"hell"
iex(5)> [l0, l1, l2, l3, l4] = ls
["Hello", "World", "from", "the", "hell"]
iex(6)> l4
"hell"
iex(7)> Enum.take(ls, 4) ++ ["iex", "shell"]
["Hello", "World", "from", "the", "iex", "shell"]
如您所见,Enum.at/3 为您提供类似于a[i] 样式数组访问的内容。
如果您担心在列表中查找元素的效率 - 例如,您的输入字符串将比"Hello World from the hell" 长得多,并且您将多次按索引从中获取元素,本质上每次遍历它,您都可以从中构建一个map,并通过索引有效地查看单词:
iex(8)> with_indices = Enum.with_index(ls)
[{"Hello", 0}, {"World", 1}, {"from", 2}, {"the", 3}, {"hell", 4}]
iex(9)> indices_and_words = Enum.map(with_indices, fn({a, b}) -> {b, a} end)
[{0, "Hello"}, {1, "World"}, {2, "from"}, {3, "the"}, {4, "hell"}]
iex(10)> map = Map.new(indices_and_words)
%{0 => "Hello", 1 => "World", 2 => "from", 3 => "the", 4 => "hell"}
iex(11)> map[0]
"Hello"
iex(12)> map[4]
"hell"