I’m trying to define a predicate where it searches a list of lists for an element and returns the level of that element. For example when searching for element:
?- elementLevel(element,[a,b,c,[d,e],[element,f]],Level).
Level = 2 .
So for every list it adds a level. I was thinking of a counter, but I don’t know how to implement that for a list traversal.
I am assuming that this is a homework assignment, so I would provide hints rather than the code. I hope this is sufficient to develop your own code, because the task at hand is only moderately complex.
You would need one fact and three rules.
The fact would ignore the element (i.e. use
_), unify the list with an empty list, and say that the returned level is -1 (not found).The first and the second rules would be the “textbook” list search, unifying the element with the head of the list, and returning the level 1; the other rule would ignore the head, and return the level of the element in the tail.
The final rule would unify the head of the list with a nested list of head and tail, make a recursive call, and check the returned value to see if it is more than zero. If it is, the return value is the nested return plus one; otherwise, recursively check the tail, and return the result of that check.