Search code examples
erlangerl

check for item in list in Erlang


I'm trying to make check function in Erlang I have one word and list of word

list_word() ->
     ["bad1", "bad2", "bad3"].

And I'm trying to check if this word in list return true except return false

example :

check_list() ->
    badword = list_word(),
    if "bad1" == badword ->
        %% do some thing

in this case first word in list but second word not and I wan't it to return true

check_list() ->
    badword = list_word(),
    if "bad1 test" == badword ->
        %% do some thing

how can I do it ?


Solution

  • Look at lists:member/2 — it is implemented as a BIF so it's very fast.

    case lists:member("bad1", list_word()) of
        true ->
            %% do something
            ;
        false ->
            ok
    end.
    

    Edit: For your second example you can do something like:

    Words = list_word(),
    Found = fun(Word) -> lists:member(Word, Words) end,
    BadWords = string:tokens("bad1 test", " "),
    case lists:any(Found, BadWords) of
        true ->
            %% do something
            ;
        false ->
            ok
    end.