0

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?

Isabelle Newbie
  • 9,258
  • 1
  • 20
  • 32
  • 1
    Can you post something you have tried that doesn't work? You will get more help more quickly if you do. – Nick Apr 28 '18 at 15:29
  • @Nick I have edited it to show what I have done –  Apr 28 '18 at 15:33

1 Answers1

1

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.

jakub1998
  • 400
  • 2
  • 13
  • 2
    The clause `list([]) :- fail.` can be removed. As no other clause matches the empty list, a call `list([])` will fail anyway. – Isabelle Newbie Apr 28 '18 at 17:06
  • @IsabelleNewbie Of course, but I found my code more understandable for new prolog users, that's why I wrote the line after lines of code :) – jakub1998 Apr 29 '18 at 07:55
  • That's what I guessed. IMHO it's important for beginners to learn that whatever isn't explicitly defined to suceed will fail, but you may see it differently. – Isabelle Newbie Apr 29 '18 at 11:59