Prolog (Sicstus) - setof 和 findall 组合问题 [英] Prolog (Sicstus) - setof and findall combination issues

查看:38
本文介绍了Prolog (Sicstus) - setof 和 findall 组合问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个给定车站的一组路线,例如我们:

Given a set of routes a given station has, such us :

route(TubeLine, ListOfStations).

route(green, [a,b,c,d,e,f]).
route(blue, [g,b,c,h,i,j]).
...

我需要找到具有共同特定车站的线路名称.结果必须是有序的,没有重复站,如果没有结果,必须返回一个空列表.所以,查询

I am required to find names of lines that have a specific station in common. The result must be ordered, with non-repeated stations and must return an empty list, if there were no results. So, querying

| ?- lines(i, Ls).

应该给:

Ls = [blue,red,silver] ? ;
no

我尝试执行以下操作:

lines(X, L) :- setof(L1, findall(W, (route(W, Stations),member(X, Stations)),L1), L).

然而,它给出了以下答案:

However, it gives the following as an answer:

Is = [[blue,silver,red]];
no

所以用双花括号无序.我尝试只使用 findall,但结果没有排序.我知道然后我可以编写 sort 函数并传递它,但是我想知道在这种情况下是否可以只使用 findall 和 setof?

So unordered with double braces. I tried using just findall, but the result is not ordered. I know I could then write sort function and pass that through, however I was wondering if it is possible to use just findall and setof in this instance?

推荐答案

实际上,这比您的尝试更容易,但是您需要掌握自由变量的特殊 setof 行为,并考虑到需要未知站的可能性(如果没有解决方案,setof/3 会失败).

Actually, it's easier than your attempt, but you need to grasp the peculiar setof' behaviour wrt free variables, and account for the eventuality that an unknown station was required (setof/3 fails if there are no solutions).

 lines(X, Ls) :-
   setof(L, Stations^(route(L, Stations), member(X, Stations)), Ls)
   -> true ; Ls = [].

如您所说,更简单的替代方法是完全按照您的方式使用 findall/3(不带 setof!),并对输出进行排序.

An easier alternative, as you said, use findall/3 exactly as you're doing (without setof!), and sort the output.

这篇关于Prolog (Sicstus) - setof 和 findall 组合问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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