Programming ยท Free practice
Prolog: Counting in a List
Write a relation c5 that counts the 5s in a list of any length. Watch the lesson by Dr. J. Ubaldo Quevedo, then practice as many times as you want: every New button gives you a new list or a new program.
1. Watch
The solution:
c5([], 0).
c5([5|T], P) :- !, c5(T, X), P is X + 1.
c5([_|T], P) :- c5(T, P).
- Base case: the empty list has zero 5s.
- [5|T] matches a list whose head is 5: count the tail, then add 1.
isdoes the arithmetic. - [_|T] matches any other list: the count is the count of the tail. The cut
!stops a 5 from also matching this clause when Prolog backtracks.
2. Try it yourself
Practice as many times as you want. Every New button builds a new list or program. It's free, and you don't need an account or a Prolog installation.
Correct so far: 0