Question

Using Erlang, I have the following expression:

{add,{var,a},{mul,{num,2},{var,b}}}

and I am using lists:keymember to see whether the letter b is within the expression as such:

lists:keymember(b,2,[expr])

However, it doesn't look within the third tuple '{mul,{num,2},{var,b}' as that is a separate tuple. Is there a function that will search through the whole tuple and tuples within?

Thanks

Was it helpful?

Solution

As far I as I know there are no such functions. Probably you will have to implement some custom solution using recursion. Here is my example:

-module(test).
-compile(export_all).

find(_, []) -> false;

find(E, T) when is_tuple(T) ->
    find(E, tuple_to_list(T));

find(E, [H|T]) ->
    case find(E, H) of
        false -> find(E, T);
        true -> true
    end;

find(V, E) -> V == E.

And usage:

1> test:find(b, {add,{var,a},{mul,{num,2},{var,b}}}).
true
2> test:find(b, {add,{var,a},{mul,{num,2},{var,c}}}).
false

OTHER TIPS

Please review your code.

  • Line1: this is a tree, not a list.
  • Line2: expr is not a variable.

What you want to do is a visitor function, and you'll have to write it yourself. A very good start would be to read this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top