【发布时间】:2021-03-03 16:29:42
【问题描述】:
我正在尝试通过将映射的值与作为字符串的给定输入进行比较来打印键(输入在下面尝试执行的示例输出中给出)。
请看下面我试过的代码:
-module(main).
-compile(export_all).
get_code_for_words(Sentence) ->
Words = string:split(Sentence, "\s", all),
LettersWords = # { "a" => ".- ","b" =>"-... ","c" =>"-.-. ","d" => "-.. ","e" => ". ","f" => "..-. ","g" => "--. ","h" =>".... ","i" =>".. ","j" =>".--- ","k" =>"-.- ","l" =>".-.. ","m" =>"-- ","n" =>"-. ","o" => "--- ","p" =>".--. ","q" =>"--.- ","r" =>".-. ","s" =>"... ","t" =>"- ","u" =>"..- ","v" =>"...- ","w" =>".-- ","x" =>"-..- ","y" =>"-.--","z" =>"--.. "},
Result = get_codes(Words, LettersWords, _AllCodes=[]),
io:format("~p~n", [Result]).
get_codes([Word|Words], Map, AllCodes) ->
NewAllCodes = maps:fold(fun(K,V,Acc) ->
%io:format("~p~n",[Acc]),
case V =:= Word of
true -> [K|Acc];
_ -> Acc
end
end,
AllCodes,
Map),
get_codes(Words, Map, NewAllCodes);
get_codes([], _Map, AllCodes) ->
lists:reverse(AllCodes).
当我执行代码时,输出如下:
**
9> c(main).
main.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,main}
10> main:get_code_for_words(".... ..").
[]
ok
**
请给我建议?
【问题讨论】:
-
感谢 7stud 的解释,我尝试使用您提供的示例函数 get_code_for_words(Sentence) 来满足我的要求。该函数获取一个句子并将其拆分为单词,然后依次获取每个单词并查看映射中的每个值以找到该单词的匹配项,如果找到匹配项,则将匹配值的键添加到累加器。它工作正常,但输出正在打印。请推荐我?
-
地图中的值都不是
"...."或"..",那么您希望输出是什么? -
在定义的 Map ("a" => ".- ","b" =>"-... ",) 中,我只是去掉了 Map(And我的地图将是 ("a" => ".- ","b" =>"-...",)。然后将值与输入进行比较,我执行并得到所需的输出。谢谢@7Stud。
标签: erlang erlang-shell