Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count only the number elements in a list (PROLOG) [duplicate]

Tags:

prolog

count([],0).
count([_|Tail], N) :- count(Tail, N1), N is N1 + 1.

This count all the elements, but I need to count only the numbers.

like image 619
Alexandre Rocha Avatar asked Nov 30 '25 01:11

Alexandre Rocha


1 Answers

Prolog has an ISO builtin predicate number/1 that checks whether the given parameter is a number.

We can simply use an if-then-else statement that either increments N is N1+1, or sets N = N1, like:

count([],0).
count([H|Tail], N) :-
    count(Tail, N1),
    (  number(H)
    -> N is N1 + 1
    ;  N = N1
    ).
like image 173
Willem Van Onsem Avatar answered Dec 01 '25 23:12

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!