0

I have a some problem understaing the flow of prolog. here is the code:

h(X):- 1 is X mod 2, write(X), nl, 0 is X mod 3, !, fail.
h(_).
t(_,[],0).
t(M,[_|LS],1):-member(M,LS),write('member'), nl,fail.
t(_,[H|_],H).
r([X|LS],R):-h(X), M is 2*X+1,t(M, LS, R), write(R), nl, fail.

now I am runing 3 things: 1. r([3,7,9],R). 2. r([5,11,13],R). 3. r([2,3,5],R). and I cant understand the answers I get. the answers are: 1. 3 false. 2. 5 11 false. 3. member 3 false.

hope for help!

false
  • 10,264
  • 13
  • 101
  • 209
  • What answers were you expecting? Note that a cut followed by `fail` results in "false" since the cut eliminates backtracking. Therefore, in your definition of `h/1`, if `1 is X mod 2` and `0 is X mod 3` succeed, then `h(X)` will necessarily fail, and then `h(X), M is 2*X + 1, ...` won't ever get past the `h(X)` query. It's unclear to me why you'd want to use `!, fail` in `h/1` at all. It's a very poor way to enforce conditions for a predicate clause to be applicable or not. – lurker Jul 09 '17 at 12:33
  • thank you. it is a question from an exam actually. I really dont get the use of the cut here.. in r([5,11,13],R). why do I get 11 at all? – user4485863 Jul 09 '17 at 12:45
  • Have you done any reading about how Prolog works? Have you tried doing a `trace.` and then running the queries to see what the code does? Before doing the `trace` it's good to understand the meaning of *backtracking* and how that's a basic Prolog behavior. – lurker Jul 10 '17 at 02:12
  • thank you. what I have trouble understanding is why do we get 11..and not member . h(X) is satisfied with X=5 and 5 is printed, then we continue with t(11,[11,13],R) and we get into the second role, so I cant understand why are we printing 11 and why not printing member? – user4485863 Jul 11 '17 at 08:39
  • Because you have `t(M,[_|LS],1) :- member(M,LS),write('member'), ...`, so `t(11, [11,13], R) :- ...` is checking `member(11, [13])` which fails. – lurker Jul 11 '17 at 11:04
  • ohh right. thanks a lot – user4485863 Jul 12 '17 at 14:21

0 Answers0