Search code examples
recursionprologpredicates

Prolog Recursive Predicates


Give recursive definition in Prolog: Define a predicate that holds of an argument X if and only if X is a list and the length of X is odd.

I have been trying to solve this for ages. I am just wanting to learn ProLog for myself and found this problem in a book.

I have tried this but it probably only works for lists of even length.

mult2_length( [] ).
mult2_length( [ _, _ | Xs ] ) :-
  mult2_length( Xs ).

Can anyone please help me?


Solution

  • You have to have predicates like these:

    list([]) :- fail.
    list([_]).
    list([_,_|T]) :- list(T).
    

    You just keep removing 2 elements from list until there are 0 or 1.