JavaScript Array.map的Elixir等价实现及重复单词查找方案
Elixir提取句子中重复单词的实现方法
问题背景
我是Elixir新手,已经能用JavaScript实现提取句子中的重复单词,但因为Elixir的不可变性特性,不知道怎么转换成Elixir版本。以下是我的JS实现和尝试的Elixir代码,求正确实现方式。
JavaScript实现代码
const str = "This is the state of education? is It?" words = str.split(" "); const data = new Set(words.map((word) => { if(words.filter((value) => value == word).length > 1){ return word } }).filter(value => value != undefined) ) // Set(1) {'is'}
尝试的Elixir代码
defmodule Test do def find_duplicate_words(sentence) do words = String.split(String.downcase(sentence)) ls = [1,2] Enum.map(words, fn word -> # if "fox" == word do [ls | word] # end end ) IO.puts(ls) IO.puts(length(words)) end end sentence = """ This is the state of education? is It? """ # returns ["is"] <-- return this Test.find_duplicate_words(sentence)
正确的Elixir实现
利用Elixir的Enum模块可以高效实现需求,核心思路是先统计每个单词的出现频率,再筛选出重复的单词并去重:
defmodule Test do def find_duplicate_words(sentence) do sentence |> String.downcase() |> String.split() |> Enum.frequencies() |> Enum.filter(fn {_word, count} -> count > 1 end) |> Enum.map(fn {word, _count} -> word end) end end sentence = "This is the state of education? is It?" IO.inspect(Test.find_duplicate_words(sentence)) # 输出: ["is"]
代码解释
String.downcase():把整个句子转成小写,确保大小写不影响重复判断(比如原句中的"is"和"It?"转小写后是"is"和"it?",不会被误判为重复)String.split():默认按空白字符分割句子成单词列表Enum.frequencies():统计列表中每个元素的出现次数,返回一个%{word => count}的映射Enum.filter/2:过滤出出现次数大于1的键值对Enum.map/2:提取出这些重复的单词,最终得到重复单词的列表
内容的提问来源于stack exchange,提问作者ONEPOINTONE
相关产品推荐
相关产品推荐

