to count no of elements in list using prolog programming?

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?

Replies

  • Manish Goyal
    Manish Goyal
    Please refer Logic an Prolog Programming by Saroj Kaushik

    Page n0 180 😉
  • Deepika Bansal
    Deepika Bansal
    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.😀

You are reading an archived discussion.

Related Posts

Do you wish to publish an article on our official blog 'VoiCE'? You can do so right away. Just compose a 100% original article (without any copy-pasted content) and send...
Hi, Check my project, Scrolling displays in numeric. In this project i have used basic logical IC's which are common to all student. here is the list of component used....
Just downloaded Mozilla Firefox 4. I wanted to try some themes on the new firefox. Could anyone share a few useful resources? 😒
It might be silly, but I'm not able to figure out how to upgrade Firefox to latest stable 4.0. I've searched the Internet but can't find proper instructions on how...
I came across this excellent article and I want each one of you to read it. It SHOULD be an eye opener for those who aren't aware. I look forward...