Guard `in` list doesn't work in function's parameters

Hello , I have 3 fn which create and check list, but it does not work for me .

for example :

list creator :

defp string_to_array(string) when is_binary(string) do
        String.split(string, [" ", ","])
end

and check fn :

defp merge_db_plug_category(query, group_acl) when group_acl in ["admin"] do
		IO.puts "1"
		IO.inspect group_acl
end

defp merge_db_plug_category(query, group_acl)  do
		IO.puts "2"
		IO.inspect group_acl
end

I get ["admin"] list when I send and inspect group_acl, but always merge_db_plug_category(query, group_acl) works , why doesn’t when group_acl in ["admin"] work for me ?

how can I check list in function parameters ?

[:foo] is not in [:foo], but :foo is.

3 Likes

Then , how can I check ["admin", "admin2"] in list in function parameters ?

Afaik you cannot do that in guards or via pattern matching.

How about

Enum.reduce(group_acl, query, fn 
  "admin", query -> 
    IO.puts "1"
    query
  _, query -> 
    IO.puts "2"
    query
end)
2 Likes

Set functions aren’t expressable in a guard safe way you need to move the check into the body of the function or use recursion over the list and build a map of valid entries/roles where you then can again pattern match on.

3 Likes

Well they are more easily done so if they use a map instead of a list, especially with the new OTP 21 features. :slight_smile:

2 Likes