给定一个给定站点的路由,例如我们:
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] ? ; noI 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]]; noSo 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.
更多推荐
发布评论