Prolog(Sicstus)

编程入门 行业动态 更新时间:2024-10-24 10:25:23
Prolog(Sicstus) - setof和findall组合问题(Prolog (Sicstus) - setof and findall combination issues)

给定一个给定站点的路由,例如我们:

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

我需要查找具有特定站点的行的名称。 结果必须是非重复的站点,如果没有结果,必须返回一个空列表。 所以,查询

| ?- lines(i, Ls).

应该给:

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

我尝试过以下操作:

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

但是,它给出了以下答案:

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

双括号无序。 我尝试使用findall,但结果没有订购。 我知道我可以编写sort函数并通过它,但是我想知道在这个实例中是否可以使用findall和setof?

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).

Should give:

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

I tried doing the following:

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

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 / 3就会失败)。

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

如你所说,更容易的替代方法是使用findall / 3,就像你正在做的那样(没有setof!),并对输出进行排序。

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 = [].

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

更多推荐

本文发布于:2023-07-09 02:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1082881.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Prolog   Sicstus

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!