prolog - Collecting Items and Counting the Number of Occurrences -
i trying write recursive rule collcount/2
groups identical items in list respective numbers of occurrences tuples.
for example, collcount([a,b,a,b,c,b],f)
binds f
[(a,2),(b,3),(c,1)]
. when running query, prolog returns no
.
the following have managed far:
collcount([h|t],[(h,n)|l2]) :- countdel(h,[h|t],l,n), collcount(l,l2). countdel(x,t,rest,n) :- occur(x,t,n), delall(x,t,rest). occur(_,[],0). occur(x,[x|t],n) :- occur(x,t,nn), n nn + 1. occur(x,[h|t],n) :- occur(x,t,n), x \= h. delall(_,[],[]). delall(x,[x|t],ans) :- delall(x,t,ans). delall(x,[h|t],[h|rest]) :- delall(x,t,rest), x \= h.
the predicate countdel/4
counts , deletes occurrences of specific item in list. instance, countdel(2,[1,2,3,2,2],l,n)
binds l [1,3]
, n
3
.
the predicate occur/3
counts occurrences of specific item in list. instance, occur(3,[1,2,3,4,3],num)
binds num
2
.
the predicate delall/3
deletes occurrences of specific item in list. instance, delall(3,[1,2,3,4,3],l)
binds l
[1,2,4]
.
any appreciated.
your code correct. i've placed comments modified it.
collcount([],[]). % miss base case collcount([h|t],[(h,n)|l2]) :- countdel(h,[h|t],l,n), collcount(l,l2). countdel(x,t,rest,n) :- occur(x,t,n), delall(x,t,rest). occur(_,[],0). occur(x,[x|t],n) :- occur(x,t,nn), n nn + 1. occur(x,[h|t],n) :- occur(x,t,n), x \= h. delall(_,[],[]). delall(x,[x|t],ans) :- delall(x,t,ans). delall(x,[h|t],[h|rest]) :- x \= h, % moved before recursive call delall(x,t,rest).
this yields
?- collcount([a,b,a,b,c,b],f). f = [ (a, 2), (b, 3), (c, 1)] ; false.
Comments
Post a Comment