CrazyEngineers
  • to count no of elements in list using prolog programming?

    bohar

    bohar

    @bohar-wQr9Oe
    Updated: Oct 25, 2024
    Views: 1.5K
    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?
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • Manish Goyal

    MemberMar 22, 2011

    Please refer Logic an Prolog Programming by Saroj Kaushik

    Page n0 180 😉
    Are you sure? This action cannot be undone.
    Cancel
  • Deepika Bansal

    MemberMar 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.😀
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register