0
        findThree([H|T],_,3).    
        findThree([H|T], M, Z):-
            ( member(H,M)
              -> Z2 is Z + 1,
              select(H,M,C),
              findThree(T,C,Z2)
              ;select(H,M,C),
              findThree(T,C,Z)
            ).

So, what I'm trying to do is see if an element is in a specified list. If it is, I increment some variable, and stop if I found 3 of those elements. However, this does not seem to be working for me- is it a problem with my syntax? I'm trying to use an If-else construct in SWI-Prolog; could that be the issue?

false
  • 10,264
  • 13
  • 101
  • 209
Waffles
  • 1
  • 2
  • I don't know much about prolog, but I do know that "incrementing a variable" is something you can't do. Try a more declarative approach (I know that's not very helpful). – luqui Feb 27 '11 at 23:15

1 Answers1

1

Z is Z + 1 will always fail for integers; that will compute the value of Z + 1 and then try to unify it with Z. Since Z will generally not have the same value as Z + 1, the is will fail. You will need to create a new variable Z2, use Z2 is Z + 1, and then use Z2 instead of Z in relevant places.

Taking your code and making fixes:

findThree(_,_,3).  % This should allow anything as the first element

findThree([H|T], M, Z) :-
  select(H, M, C), Z2 is Z + 1, findThree(T, C, Z2). % select includes member implicitly
findThree([_|T], M, Z) :-
  findThree(T, M, Z). % Allow this second case since it simplifies the code
Jeremiah Willcock
  • 30,161
  • 7
  • 76
  • 78
  • Well, that works if I want to find one item, but for three items, it fails. – Waffles Feb 28 '11 at 00:30
  • Normally, you don't write Prolog with if-then-else clauses, just backtracking. You want to find `N` copies of a value `M`, right? I couldn't quite tell from your question description. – Jeremiah Willcock Feb 28 '11 at 01:01
  • Well, I want to find how many elements in a list A are in a list B. In this case, I'm trying to find out if there are 3 elements in A that are also in B. – Waffles Feb 28 '11 at 01:42
  • @Waffles: Is that first statement in your program (`findThree([H|T],_,3).`) actually the query you are running? – Jeremiah Willcock Feb 28 '11 at 02:18
  • @Waffles: See the new code I put in my answer; I think it fixes the issues and makes things simpler. – Jeremiah Willcock Feb 28 '11 at 02:29