1

I wanna build a predicate that given a List of lists and a Element with coordinates X, checks if X belong to any list inside that main List, and if it belongs to any list, returns the ReturnList as a list with elements up until the position of where the Element X is found.

So for example, given;

?-checklist((3,4),[[(1,3), (1,2), (1,1)],[(1,4), (2,4), (3,4), (4,4)]], ReturnList)

returns

ReturnList = [(1,4), (2,4), (3,4)]

I'm trying to implement this and so far I have

get_list([],_,[]).
get_list([List], Element, ReturnList):- 
  member(List, Element),
  get_list(List|Rest, Element, List).

But It's one of my first prolog programs and I'm finding it difficult to grasp the logic

false
  • 10,264
  • 13
  • 101
  • 209
spacing
  • 730
  • 2
  • 10
  • 41

1 Answers1

2

My solution (with comments) using Prolog builtins member/2 and append/3:

checklist(Elem, List, ReturnList) :-
    member(SubList, List),          % SubList is contained in List
    member(Elem, SubList),          % Elem is contained in SubList
    append(ReturnList, _, SubList), % ReturnList is a prefix of SubList
    append(_, [Elem], ReturnList).  % Elem is the last element of ReturnList

Test:

?- checklist((3,4),[[(1,3), (1,2), (1,1)],[(1,4), (2,4), (3,4), (4,4)]], ReturnList).
ReturnList = [(1, 4),  (2, 4),  (3, 4)] ;
false.
fferri
  • 18,285
  • 5
  • 46
  • 95