Replies
Welcome, guest
Join CrazyEngineers to reply, ask questions, and participate in conversations.
CrazyEngineers powered by Jatra Community Platform
-
@manish-r2Hoep • Mar 22, 2011
-
@deepika-jf1ysv • Mar 25, 2011
Hehe that was a short and a sweet answer Manish.
But let me give the facts so that it may proved beneficial for other CEans as well.
/* Let L be the list (represented as [H|T] ) that stores the elements to be counted. Let N be the number of elements in the list. count(L,N)- succeeds if N is unified (matched) with the length of the list L. */ count([],0). count([H|T],N) :- count(T,N1) , N is N1+1.
Explanation: The recursive method needs one boundary statement (fact 1) and another recursive call (fact 2).
The recursive call will be made to the tail 'T' of the list L and the count variable Ni's are stored in the stack meanwhile. This will continue until it reaches the boundary condition ie when the list becomes empty. Then the count variable will be instantiated to 0 and corresponding Ni's will be calculated.
At the end the final result will be displayed by the prolog compiler.😀