Prolog中的列表处理计算以找到朋友将访问的目的地 [英] List processing calculation in Prolog to find a destination friends will visit

查看:8
本文介绍了Prolog中的列表处理计算以找到朋友将访问的目的地的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个谓词来计算一组朋友将访问的目的地.朋友们这样列出他们喜欢的国家/地区

I'm trying to write a predicate that calculates which destination a group of friends will visit. The friends list their countries of preferences like this

choice(marie, [peru,greece,vietnam]). 
choice(jean, [greece,peru,vietnam]). 
choice(sasha, [vietnam,peru,greece]). 
choice(helena,[peru,vietnam,greece]). 
choice(emma, [greece,peru,vietnam]).

我想编写一个名为 where 的谓词,它需要 2 个参数来执行计算.我想到的公式是,第一个国家值 3 分,第二个国家值 2 分,最后一个国家值 1 分.

I want to write a predicate called where that takes 2 arguments to perform the calculation. The formula I have in mind is that the first country is worth 3 points, the second one is worth 2 points, and the last one is worth 1 point.

这是我想要实现的一个示例.

Here's an example of what I'm trying to achieve.

?- where([marie,jean,sasha,helena,emma],Country). 
peru .

到目前为止我有这个

where([], X).
where([H|T], N) :- choice(H, [A|B]), where(T,N).

它让我可以遍历所有不同的朋友并显示他们的选择,但我无法遍历选择列表并将点分配给目的地.

It lets me iterate through all the different friends and shows their choices but I can't iterate through the list of choices and assign points to the destinations.

我应该如何遍历每个朋友的选择列表并分配积分来计算最佳目的地?

How should I go about iterating through the list of choices for each friend and assigning points to calculate the best destination?

推荐答案

根据 GuyCoder 的建议,您需要一个累加器来汇总每个人的偏好,并且 foldl/N 允许这样做.

As suggested by GuyCoder, you need an accumulator to sum each person preferences, and foldl/N allows to does exactly this.

choice(marie, [peru,greece,vietnam]).
choice(jean,  [greece,peru,vietnam]).
choice(sasha, [vietnam,peru,greece]).
choice(helena,[peru,vietnam,greece]).
choice(emma,  [greece,peru,vietnam]).

where(People,Where) :-
    foldl([Person,State,Updated]>>(choice(Person,C),update(State,C,Updated)),
          People,
          [0=greece,0=peru,0=vietnam],
          Pref),
    aggregate(max(S,S=W),member(S=W,Pref),max(_,_=Where)).
%    sort(Pref,Sorted),
%    last(Sorted,_=Where).

update(S0,[A,B,C],S3) :-
    update(S0,3,A,S1),
    update(S1,2,B,S2),
    update(S2,1,C,S3).

update(L,V,C,U) :-
    append(X,[Y=C|Z],L),
    P is Y+V,
    append(X,[P=C|Z],U).

我已将最后两个目标的注释留下来替换为单个目标聚合/3,因此您可以尝试理解语法...

I have left commented the last two goals replaced by the single goal aggregate/3, so you can try to understand the syntax...

这篇关于Prolog中的列表处理计算以找到朋友将访问的目的地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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