Search code examples
listprologvisual-prolog

Prolog lists splitting


I have function:

onlySecond([],[]).

onlySecond([H1,H2|T1],[H2|T2]) :- onlySecond(T1,T2).

It returns every second element in the list.

But i'm curious why it is not returning nothing (on my opinion, it must return [] - empty list) when first argument is list with 1 element. Example:

onlySecond([1],X). - not return anything.. but why it doesn't return []??

Solution

  • Your program has a bigger problem: it returns false for any list of odd size. The reason for it is that there is no clause of onlySecond/2 that would unify with a list that has exactly one item - a condition that you would necessarily reach when you start with a list that has an odd number of items, because each recursive invocation reduces the length of the original list by two:

    • it does not unify with the first clause, because [1] is not an empty list
    • it does not unify with the second clause, because [1] has fewer than two items.

    In order to fix this problem, add a separate clause to deal with a list that has exactly one item:

    onlySecond([_], []).
    

    Adding this clause makes your code work for lists of odd length as well.

    Demo.