I know some questions here are similar to this one, but I'm inexperienced and I don't know how to use them and convert the solutions to my problem ;/
I have a list with lists inside, like this one:
[ [5],[4,7],[1,2,7],[2,6,7],[2,4,6,7],[2,4,7],[9,8],[3],[1] ]
and I need to know the index of, e.g., the number 3. The number I need to know will only appear on the list of lists once, that's a previous condition to call the function. The index I need is, for the number 3, the index 9 (starts at 1). I had this draft of a function:
given_elem_finds_pos(ListOfLists, Element, Pos):-
nth1(Pos, ListOfLists, [Element|_]).
But it only returns the Pos if the Element is the head of a sublist. I need to know how to get to the index of e.g. the number 8.
Then I did this one:
given_elem_finds_pos( [[H|T]| R], Element, Ind):-
member(Element, [H|T]),
Ind1 is Ind + 1,
given_elem_finds_pos(R, Element, Ind1).
But again, not successful.. Can anyone help? Thank you so much!
Your second approach is going into the right direction. Just think what you want to describe: If Element
is an element of [H|T]
you want to stop, hence, no need to have a recursive call here. Furthermore, you would like to return the current index, thus you need an extra argument (one for the counter and one for the final index). The recursive clause is needed for the case that Element
is not an element of the list. Here is the clause for the case that it is an element
given_elem_finds_pos( [List| R], Element, Solution,Solution):-
member(Element, List).
As you have to add the extra argument you need an additional predicate that calls your extended predicate:
given_elem_finds_pos(ListOfLists, Element, Ind):-
given_elem_finds_pos(ListOfLists, Element,0, Solution).
Now you only have to write one more clauses for given_elem_finds_pos/4
, a recursive one for the "it's not an element" case. Ask, if you have trouble writing this clause.