Home > Archive > Prolog > March 2006 > Count the atoms
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
|
|
| Sweet.mhtrq@gmail.com 2006-03-21, 10:04 pm |
| Hi everyone, i'm new to prolog.
and I'm looking for a method to count the atoms in a list(include the
elements within any sublist).
thanks
| |
| Bart Demoen 2006-03-21, 10:04 pm |
| Sweet.mhtrq@gmail.com wrote:
> Hi everyone, i'm new to prolog.
> and I'm looking for a method to count the atoms in a list(include the
> elements within any sublist).
> thanks
>
It's not completely clear what you want, but start by looking for
flatten/2, sort/2, and length/2
You might benefit from looking for filter/3 as well
Cheers
Bart Demoen
| |
| Erik Braun 2006-03-21, 10:04 pm |
| Sweet.mhtrq@gmail.com <Sweet.mhtrq@gmail.com> wrote:
> and I'm looking for a method to count the atoms in a list(include the
> elements within any sublist).
Why don't you just flatten the list and count the atoms straight forward?
c([],0).
c([H|T],X) :- atom(H), c(T,Y), X is Y+1.
c([_|T],X) :- c(T,X).
(I forgot a cut somewhere. Without it, you teacher will not be happy).
| |
| michael.goodrich@gmail.com 2006-03-23, 7:03 pm |
|
Erik Braun wrote:
> Sweet.mhtrq@gmail.com <Sweet.mhtrq@gmail.com> wrote:
>
>
> Why don't you just flatten the list and count the atoms straight forward?
>
> c([],0).
> c([H|T],X) :- atom(H), c(T,Y), X is Y+1.
> c([_|T],X) :- c(T,X).
>
> (I forgot a cut somewhere. Without it, you teacher will not be happy).
But this looks left-recursive which is a no-no. How about
count_atoms(Lst,Cnt) :- c1(Lst,0,Cnt).
c1([],C,C).
c1([H|T],C,Acc) :- atom(H), !, C1 is C+1, c1(T,C1,Acc).
c1([_|T],C,Acc) :- c1(T,C,Acc).
where 'count_atoms' is written to hide the accumulator passing from the
caller, and this is right-recursive (with the cut).
cheers,
-Mike
|
|
|
|
|