序言列出递归的每一个可能的路径 [英] prolog list out every possible path of the recursion

查看:47
本文介绍了序言列出递归的每一个可能的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想列出所有可能的路径

I would like to list out every possible path

country(england,france). 
country(france,bulgaria).
country(bulgaria,germany).
country(england,bulgaria).
country(germany,italy).
edit: additional to

country(germany,italy).
country(england,italy).
country(england,greece).
country(greece,france).

connectto(X, Y) :-
country(X, Y).

?-op(150,xfy,to).

?-op(150,xfy,to).

X to Y:-get_waypoints(X,Y,Waypoints),write(Waypoints),fail.

X to Y:-get_waypoints(X,Y,Waypoints),write(Waypoints),fail.

get_waypoints(Start, End, [Waypoint|Result]) :-
   country(Start, End),
   !;country(Start, Waypoint),
   get_waypoints(Waypoint, End, Result).

否则从原始代码系统会给出

otherwise from the original code the system will give out

   | ?- england to italy.
   []no

来自您提到的代码.

问题来了

    | ?- england to italy.
    [_31242|_31243][france,bulgaria,germany,_31332|_31333]   
    [bulgaria,germany,_31422|_31423]
    [greece,france,bulgaria,germany,_31602|_31603]no

虽然它显示了所有可能的路线.

although it shows out all possible route.

任何解决方案将不胜感激.

Any solution will be appreciated.

推荐答案

询问是否需要解释:

country(bulgaria,germany).
country(england,bulgaria).
country(england,france). 
country(england,greece).
country(england,italy).
country(france,bulgaria).
country(greece,france).
country(germany,italy).

:- op(150, xfy, to).

X to Y :-
    findall(Waypoint, get_waypoints(X,Y,Waypoint), Waypoints),
    write(Waypoints).

get_waypoints(Start, End, []) :- 
    country(Start, End).
get_waypoints(Start, End, [Waypoint|Result]) :-
    country(Start, Waypoint),
    get_waypoints(Waypoint, End, Result).

用途是:

?- england to italy.

在这里,我更新了我的代码以符合您的期望.

Here, I updated my code to match your expectations.

这篇关于序言列出递归的每一个可能的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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