CrazyEngineers Archive
Old, but evergreen and popular discussions on CrazyEngineers, presented to you in read-only mode.
@bohar • 22 Mar, 2011

if there is list L like [1,4,5,23,4,43] then what are rules or procedure required to count the element of list using recursion in prolog?

@Manish Goyal • 22 Mar, 2011 Please refer Logic an Prolog Programming by Saroj Kaushik

Page n0 180 😉
@Deepika Bansal • 25 Mar, 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([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.😀

Related Posts

@Ankita Katdare · Feb 23, 2014

A lot of engineers among us might be trying to go for MBA after their graduation in B.E. or B.Tech.If you face a personal interview for any MBA college, you...

@Ankit Sood · Jan 28, 2015

Project Abstract / Summary : LPG gas is supplied in pressurized steel cylinders. As this gas is heavier than air, so when it leaks from a cylinder it flows along...

@rengaraj · Dec 19, 2009

Sir / madam, My question is A man buys 12 lts of liquid which contains 20% of the liquid and the rest is water. He then mixes it with 10...

@Ankita Katdare · Jul 3, 2013

Nissan has launched it's two new variants to the Nissan Micra car with a facelifted 2013 version and the Nissan Micra Active XE. After having sold more than 43,000 units...

@deepika mishra · Sep 13, 2010

What is the difference between Multi-programming and Multi-tasking? Please illustrate with an example.