0

I'm looking to define a function plak/3 such that plak(X,Y,Z) returns true when appending Y to X results in Z. So some sample cases:

?- plak([1,2], [2,3], [1,2,2,3]).
true
?- plak([1,2,3], [4,5], X).
X = [1,2,3,4,5].
?- plak(X,[2,3,4],[1,2,3,4]).
X = [1].

Now my idea was to do

plak([],[],[]).
plak([X|Xs], Y, [Z|Zs]) :-
    X==Z,
    plak(Xs, Y, Zs).
plak(X, [Y|Ys], [Z|Zs]) :-
    Y==Z, 
    plak(X,Ys,Zs).

But this doesn't work.

false
  • 10,264
  • 13
  • 101
  • 209
Mitchell Faas
  • 430
  • 6
  • 19
  • You can use [concatenation](https://stackoverflow.com/questions/9348640/concatenation-of-lists-in-prolog) and then [check if lists equal](https://stackoverflow.com/questions/22545726/prolog-two-lists-are-exactly-the-same) – Udayraj Deshmukh Mar 16 '18 at 11:50
  • 1
    This is exactly what `append/3` (built in predicate) does. Here the implementation in swi: https://github.com/SWI-Prolog/swipl-devel/blob/master/library/lists.pl – damianodamiano Mar 16 '18 at 12:18
  • 1
    @damianodamiano When referencing GitHub source code files you can reference a line directly by appending #L and line number. e.g. `lists.pl#L118` - Working [link](https://github.com/SWI-Prolog/swipl-devel/blob/master/library/lists.pl#L118) – Guy Coder Mar 16 '18 at 12:24
  • `==` checks equivalence of terms, what you want to do is unify the terms which is done by `=` or simply putting the variable where you want it to be unified. – G_V Mar 16 '18 at 13:19

1 Answers1

1
%if the first list is empty, add the second list to the end of the output list
concatenate([],List2,List2).
%take the first element of the first list, put it in the output list.
%Do this for all elements until the first list is empty
concatenate([H|T], List2, [H|T2]) :- concatenate(T, List2, T2).

A list is effectively a chain of elements, where each element links to the next. A linked-list. The last atom is always [], so this allows us to end other lists by appending a list to the end of another, still open list.

Useful links to understand the underlying concepts, for beginners in Prolog:

G_V
  • 2,396
  • 29
  • 44