计数出现次数 Prolog [英] Count occurrences Prolog

查看:77
本文介绍了计数出现次数 Prolog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Prolog 的新手,正在尝试使用列表进行一些编程
我想这样做:

?- count_occurrences([a,b,c,a,b,c,d], X).X = [[d, 1], [c, 2], [b, 2], [a, 2]].

这是我的代码我知道它不完整但我正在尝试:

count_occurrences([],[]).count_occurrences([X|Y],A):-出现次数([X|Y],X,N).出现次数([],_,0).出现次数([X|Y],X,N):-出现次数(Y,X,W), N 是 W + 1.出现次数([X|Y],Z,N):- 出现次数(Y,Z,N), X\=Z.

我的代码是错误的,所以我需要一些点击或帮助 plz..

解决方案

这是我使用 bagof/3findall/3 的解决方案:

count_occurrences(List, Occ):-findall([X,L], (bagof(true,member(X,List),Xs), length(Xs,L)), Occ).

示例

?- count_occurrences([a,b,c,b,e,d,a,b,a], Occ).Occ = [[a, 3], [b, 3], [c, 1], [d, 1], [e, 1]].

工作原理

bagof(true,member(X,List),Xs) 对于列表 X 的每个不同元素都满足,其中 Xs 为长度等于ListX出现次数的列表:

?- bagof(true,member(X,[a,b,c,b,e,d,a,b,a]),Xs).X = a,Xs = [真,真,真];X = b,Xs = [真,真,真];X = c,Xs = [真] ;X = d,Xs = [真] ;X = e,Xs = [真].

外层 findall/3 收集元素 X 和关联列表的长度 Xs 在一个代表解决方案的列表中.>

编辑我:由于 CapelliC 和 Boris 的建议,原始答案得到了改进.

Edit II:如果给定列表中有自由变量,则可以使用 setof/3 代替 findall/3.setof/3 的问题是对于一个空列表它会失败,因此必须引入一个特殊的子句.

count_occurrences([],[]).count_occurrences(List, Occ):-setof([X,L], Xs^(bagof(a,member(X,List),Xs), length(Xs,L)), Occ).

I'm new in Prolog and trying to do some programming with Lists
I want to do this :

?- count_occurrences([a,b,c,a,b,c,d], X).
X = [[d, 1], [c, 2], [b, 2], [a, 2]].

and this is my code I know it's not complete but I'm trying:

count_occurrences([],[]).
count_occurrences([X|Y],A):-
   occurrences([X|Y],X,N).

occurrences([],_,0).    
occurrences([X|Y],X,N):- occurrences(Y,X,W), N is W + 1.
occurrences([X|Y],Z,N):- occurrences(Y,Z,N), X\=Z.

My code is wrong so i need some hits or help plz..

解决方案

Here's my solution using bagof/3 and findall/3:

count_occurrences(List, Occ):-
    findall([X,L], (bagof(true,member(X,List),Xs), length(Xs,L)), Occ).

An example

?- count_occurrences([a,b,c,b,e,d,a,b,a], Occ).
Occ = [[a, 3], [b, 3], [c, 1], [d, 1], [e, 1]].

How it works

bagof(true,member(X,List),Xs) is satisfied for each distinct element of the list X with Xs being a list with its length equal to the number of occurrences of X in List:

?- bagof(true,member(X,[a,b,c,b,e,d,a,b,a]),Xs).
X = a,
Xs = [true, true, true] ;
X = b,
Xs = [true, true, true] ;
X = c,
Xs = [true] ;
X = d,
Xs = [true] ;
X = e,
Xs = [true].

The outer findall/3 collects element X and the length of the associated list Xs in a list that represents the solution.

Edit I: the original answer was improved thanks to suggestions from CapelliC and Boris.

Edit II: setof/3 can be used instead of findall/3 if there are free variables in the given list. The problem with setof/3 is that for an empty list it will fail, hence a special clause must be introduced.

count_occurrences([],[]).
count_occurrences(List, Occ):-
    setof([X,L], Xs^(bagof(a,member(X,List),Xs), length(Xs,L)), Occ).

这篇关于计数出现次数 Prolog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆