【问题标题】:Search of element from List in the String在字符串中从 List 中搜索元素
【发布时间】:2017-05-29 14:18:14
【问题描述】:

我有一个类似List = ["google","facebook","instagram"] 的列表和一个字符串P1 = "https://www.google.co.in/webhp?pws=0&gl=us&gws_rd=cr"

现在我需要找出List 的哪个元素存在于P1 中。

为此,我在递归函数下面实现,但它返回 ok 作为最终值,有没有办法在(在这种情况下)找到 google 时,然后返回 H 并终止其他递归调用在堆栈中。

我希望这个函数返回google

traverse_list([],P1)-> ok;
traverse_list([H|T],P1) ->
 Pos=string:str(P1,H),
 if Pos > 1 ->
   io:fwrite("Bool inside no match is ~p~n",[Pos]),
   io:fwrite("inside bool nomathc, ~p~n",[H]),
   H;
 true->
   io:fwrite("value found :: ~p~n",[Pos])
 end,
traverse_list(T,P1).

【问题讨论】:

  • 一个问题是io模块的输出函数如果成功则返回ok。您可以使用 io_lib 库再次尝试您的代码,看看会发生什么。

标签: string list erlang


【解决方案1】:

它返回ok,因为你的递归循环的停止条件做到了:

traverse_list([],P1)-> ok;

为此,您应该使用lists:filter/2 或列表推导:

List = ["google","facebook","instagram"],
P1 = "https://www.google.co.in/webhp?pws=0&gl=us&gws_rd=cr",
lists:filter(fun(X) -> string:str(P1,X) > 1 end,List), 
% or
[X || X <- List, string:str(P1,X) > 1],

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多