Search code examples
erlangerl

Erlang: check chars in inserting text if chars exists in list


What I'm looking for is, if inserted text contains chars and integer and if these not in List chars return false

Example List:

List = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "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"]

And the function should have 1 value like :

check(Text) ->
    List = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "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"],

if the inserting text like is :

check("you should have 10 point to do this")

should return true cuz every thing in text exists within List

and if the inserting text like is :

check("you should + have ....")

should return false cuz " + " & " . " not exists within List.


Solution

  • Note that your first check example passes a string containing whitespace, which is not in List, so I'm assuming you want to handle that.

    Here's one way to solve this:

    check(Text) ->
        List = "1234567890abcdefghijklmnopqrstuvwxyz \t\n.",
        lists:all(fun(C) -> lists:member(C, List) end, Text).
    

    First, note that here, List is not a list of strings, as you originally specified, but a list of characters. I've added the space, tab, newline, and period characters to List as well.

    The second line of check/1 walks through the list Text character by character. For each character C we check that it's a member of List. If that test returns true for all characters, then lists:all/2 returns true, otherwise it returns false.