DJPlayer
DJPlayer

Reputation: 3294

Prolog starting on Lists

I'm just learning prolog and I wanna just get started on a basic problem so I can at least know the general construction of the rest..

for example.

patt(true,l) - always works and leaves l

patt(next(char),l) - works if char is first and leaves remainder of l

the predicate patt: matches parts of a list and leaves the remaining part or fails. l = list

also what is SWI-Prolog and decent IDE on Windows.. I just downloaded it and seems pretty straight forward.. I also grabbed BProlog and looked into a couple others..

Upvotes: 0

Views: 211

Answers (1)

Nicholas Carey
Nicholas Carey

Reputation: 74227

A clearer problem statement would be nice: it's hard to tell from your question, but it sound to me like you want to match the prefix of a list and get back all the elements that aren't part of the prefix. Here's how I would do that:

match_prefix( []     , []     , []     ).
match_prefix( []     , [Y|Ys] , [Y|Ys] ).
match_prefix( [H|Xs] , [H|Ys] , Tail   ) :-
  match_prefix( Xs , Ys , Tail ).
  • if the 1st argument (the desired prefix) is an empty list, and the 2nd argument (the list to be checked for a prefix) is an empty list, then the 3rd argument (the non-prefix tail of the lists to be checked) is an empty list.
  • Otherwise...if the 1st argument is an empty list, but the second argument is a non-empty list, we've exhausted the desired prefix, so we unify the 3rd argument (the result) with the second argument (the list).
  • Otherwise...if the 1st 2 arguments are non-empty lists and their heads unify, we strip the heads off and recurse down on the tails.

That should about do it (but I can't say I've tested it, since I don't currently have a prolog to play with).

Upvotes: 1

Related Questions