Subject: Re: numPositive

From: "Richard A. O'Keefe" <[email-masked]>
Date: Mon, 20 Nov 2000 12:59:22 +1300 (NZDT)

aikGuitarist <[email-masked]> wrote:
	I'm writing a prolog predicate:
	
	% numPos(List, N) succeeds iff List is a list, and there are exactly N 
	% positive integers in it at the TOP LEVEl. 
	
	numPos([], 0).
	numPos([Head|Tail], N):-integer(Head), Head>0, X is N-1, numPos(Tail,X).
	numPos([Head|Tail], N):-numPos(Tail,X).
	
	And it throws a number exception error. ???
	
Well, yes, of course.  When you do X is N-1, what's N?	

PLEASE do not use the baStudlyCaps style for predicate names.
The underscore exists and lets us write readable names.  Let us use it!

Two ways.  Body recursive:	

	num_pos([], 0).
	num_pos([X|Xs], N) :-
	    num_pos(Xs, M),
	    ( integer(Head), Head > 0 -> N is M + 1 ; N is M ).

and tail recursive, using an accumulator parameter:

	num_pos(Xs, N) :-
	    num_pos(Xs, 0, N).

	num_pos([], N, N).
	num_pos([X|XS], N0, N) :-
	    ( integer(Head), Head > 0 -> N1 is N0 + 1 ; N1 is N0 ),
	    num_pos(Xs, N1, N).

Then there's the prettier version using filter and length, which I'll omit.