What does this code do?

I tried different examples but I still don’t know what this code is doing. I’d appreciate if someone could help me.

I thought the code may split a list in every possible way but that doesn’t seem to be right.

The code:

p([],[]).
p([X|Xs],[X|Ys]) :-
    p(Xs,Ys).
p(Xs,[_|Ys]) :-
    p(Xs,Ys).

Have you tried just giving it some made up data to see what it does?

Take a look at this StackOverflow answer. Understanding CLP(FD) Prolog code of N-queens problem

I didn’t know of the details when I started writing the answer, but I did know all of the means to find what was needed. Mostly what you need when problem solving is

  1. Don’t give up.
  2. If what you are doing is not working think of something else and try that.

I ran a couple of quick examples. While I have not double checked what I think it does based on these few examples it looks obvious.

Examples - click to expand
?- p([],L).
L = [] ;
L = [_29294] ;
L = [_29294, _30030] ;
L = [_29294, _30030, _30766] .

?- p(L,[]).
L = [].

?- p(L,[a]).
L = [a] ;
L = [].

?- p(L,[a,b]).
L = [a, b] ;
L = [a] ;
L = [b] ;
L = [].


?- p(L,[a,b,c]).
L = [a, b, c] ;
L = [a, b] ;
L = [a, c] ;
L = [a] ;
L = [b, c] ;
L = [b] ;
L = [c] ;
L = [].

What does this code do?

Click on blur to see answer. Double-click to follow link.

1 Like