prolog - Does an element exists in a list of lists? -
i want find if given element exists in list of lists. getting true if element exists somewhere first list of lists.
any advice?
memberlist(x,[[x|t1]|t2]). memberlist(x,[[h|t1]|t2]) :- memberlist(x,[t1|t2]).
the problem [[h|t1]|t2] matches given first list has at least 1 element. indeed: [[],[1,4],[2,5]] instance not unify [[h|t1]|t2].
so can solve problem adding clause:
memberlist(x,[[]|t2]) :- memberlist(x,t2). thus obtain:
memberlist(x,[[x|_]|_]). memberlist(x,[[h|t1]|t2]) :- memberlist(x,[t1|t2]). memberlist(x,[[]|t2]) :- memberlist(x,t2). the first clause uses underscores specify "not interested" in these variables. common prolog programs (probably interpreter warned t1 , t2 mentioned once).
so in case first list exhausted, move next list.
your predicate lot of "packing" , "unpacking". furthermore can make use of member/2 builtin. can rewrite it:
memberlist(x,[h|_]) :- member(x,h). memberlist(x,[_|t2]) :- memberlist(x,t2).
Comments
Post a Comment