在elixir

时间:2017-01-05 22:35:26

标签: string list elixir

我是灵药开发的新手。我在elixir中解析字符串时遇到问题。假设我有字符串“来自地狱的Hello World”。我知道我可以将此分割为String.split("Hello World from the hell")。我想知道无论如何要将此字符串的元素分配到elixir中列出?

1 个答案:

答案 0 :(得分:5)

String.split/1返回list - Elixir的基本数据结构之一,以及mapstuples。列表是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"