Domanda

In a question I recently encountered in an university level exam for logical programming, I was asked to program a Prolog predicate, odd/1, that determines whether a given value is odd.

The implementation was supposed to make use of an already given predicate s/1, which would evaluate for the successor (i.e X + 1) of a given element. This was the solution given for the implementation of the odd/1 predicate:

odd(s(0)):-!. % 1 is the first odd number
odd(s(s(X))):- odd(X). % A number s(s(X)) (i.e X + 2) is odd if X is odd as well
  1. Does the ! in the first expression actually serve any purpose? I know it prevents backtracking after this point, but there are no following expressions? Does that mean that the resolution algorithm simply stops at this point?
  2. I tried to implement the s/1 successor predicate for the sake of practicing, but was unable to do so. (How) Could one implement this predicate in Prolog?
È stato utile?

Soluzione

here is the trace without the cut

[trace] 21 ?- odd(s(s(s(0)))).
   Call: (6) odd(s(s(s(0))))
   Call: (7) odd(s(0))
   Exit: (7) odd(s(0))
   Exit: (6) odd(s(s(s(0))))
true ;
   Redo: (7) odd(s(0))
   Fail: (7) odd(s(0))
   Fail: (6) odd(s(s(s(0))))
false.

and here with the cut

[trace] 22 ?- odd(s(s(s(0)))).
   Call: (6) odd(s(s(s(0))))
   Call: (7) odd(s(0))
   Exit: (7) odd(s(0))
   Exit: (6) odd(s(s(s(0))))
true.

I think the cut has been added for efficiency...

About s/1, it's not a predicate, but a data structure. Maybe you've seen something like

integer(0).
integer(s(X)) :- integer(X).

that's actually the simplest recursive definition for the infinite domain of (positive) integers

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top