Elixir - 从 Enum.each() 获取地图
Elixir - get the map from Enum.each()
我是 Elixir
的新手,正在尝试 this exercism。以下是我的代码:
def count(sentence) do
a = sentence
|> String.downcase()
sort_a = Regex.split(~r/([^a-z(\-)]+)/, a)
|> Enum.sort()
uniq_a = Enum.uniq(sort_a)
map = Map.new(uniq_a,fn x -> { x, 0 } end)
final_map = Enum.each(map, fn {k, v} ->
Map.replace!(map, k, v + match_check(k, sort_a))
end)
final_map
end
def match_check(x, [word|words]) do
if x == word do
1
else
0
end
match_check(x, words)
end
def match_check(x, []), do: nil
目前,我卡在 Enum.each/2
,只有 return :ok
。因此我的 final_map
将得到 :ok
。我怎样才能得到结果?
如果不创建帐户就无法查看您的 link,所以我不确定问题出在哪里,但是 Enum.each/2
is designed to perform side effects, such as printing the values, so you don't normally care about the return value. For converting the values, you generally want Enum.map/2
。例如:
Enum.each(["hello", "world!"], &IO.puts/1)
Returns :ok
并打印:
hello
world!
相比于:
Enum.map(["hello", "world!"], &String.capitalize/1)
不打印任何内容,returns:
["Hello", "World!"]
从你的例子来看,我猜你是想计算一个句子中唯一单词的数量,忽略大小写。在这种情况下,使用 String.split/1
, Enum.reduce/3
, and Map.update/4
的可能解决方案是:
"a b B CC cc cC"
|> String.split()
|> Enum.reduce(%{}, fn word, counts ->
Map.update(counts, String.downcase(word), 1, &(&1 + 1))
end)
输出:
%{"a" => 1, "b" => 2, "cc" => 3}
我是 Elixir
的新手,正在尝试 this exercism。以下是我的代码:
def count(sentence) do
a = sentence
|> String.downcase()
sort_a = Regex.split(~r/([^a-z(\-)]+)/, a)
|> Enum.sort()
uniq_a = Enum.uniq(sort_a)
map = Map.new(uniq_a,fn x -> { x, 0 } end)
final_map = Enum.each(map, fn {k, v} ->
Map.replace!(map, k, v + match_check(k, sort_a))
end)
final_map
end
def match_check(x, [word|words]) do
if x == word do
1
else
0
end
match_check(x, words)
end
def match_check(x, []), do: nil
目前,我卡在 Enum.each/2
,只有 return :ok
。因此我的 final_map
将得到 :ok
。我怎样才能得到结果?
如果不创建帐户就无法查看您的 link,所以我不确定问题出在哪里,但是 Enum.each/2
is designed to perform side effects, such as printing the values, so you don't normally care about the return value. For converting the values, you generally want Enum.map/2
。例如:
Enum.each(["hello", "world!"], &IO.puts/1)
Returns :ok
并打印:
hello
world!
相比于:
Enum.map(["hello", "world!"], &String.capitalize/1)
不打印任何内容,returns:
["Hello", "World!"]
从你的例子来看,我猜你是想计算一个句子中唯一单词的数量,忽略大小写。在这种情况下,使用 String.split/1
, Enum.reduce/3
, and Map.update/4
的可能解决方案是:
"a b B CC cc cC"
|> String.split()
|> Enum.reduce(%{}, fn word, counts ->
Map.update(counts, String.downcase(word), 1, &(&1 + 1))
end)
输出:
%{"a" => 1, "b" => 2, "cc" => 3}