Rule to group two facts in prolog?

六眼飞鱼酱① 提交于 2019-12-11 07:04:41

问题


I am writing code for the London tube. I have declared facts that display the name of a station and also which line it is on. e.g.

station(aldgate,metropolitan).
station(brixton,victoria).
station(baker,metropolitan).

I'm trying to work out a rule that will check whether two stations are on the same line, and which line that is. For example, aldgate and baker are on the same line, metropolitan.

Any ideas?


回答1:


I'm trying to work out a rule that will check whether two stations are on the same line, and which line that is.

An example can be the following rule

sameLine(Stat1, Stat2, Line) :-
  station(Stat1, Line),
  station(Stat2, Line),
  Stat1 \= Stat2.

that is flexible.

It can check of a couple of station is in the same line (calling sameLine(aldgate, baker, metropolitan) return true, calling sameLine(aldgate, baker, Line) return true and unify Line with metropolitan) but can find couples of stations of a line (calling sameLine(Stat1, Stat2, metropolitan) return true two times, unifying Stat1 with aldgate and Stat2 with baker (the first time) and vice versa (the second time)).

Observe the constraint

Stat1 \= Stat2.

It's to impose that the two stations are different.

If you want that sameLine(aldgate, aldgate, Line) return true unifying Line with metropolitan, you can delete it.

If you, otherwise, want to avoid the double results (aldgate/baker and baker/aldgate, by example, calling sameLine(Stat1, Stat2, metropolitan)) you can impose that Stat1 is non only different than Stat2 but also that is "before" Stat2, replacing

Stat1 \= Stat2

with

Stat1 @< Stat2

But, in this way, you obtain true from sameLine(aldgate, baker, Line), but false (because baker isn't "before" aldgate) from sameLine(baker, aldgate, Line).



来源:https://stackoverflow.com/questions/41516888/rule-to-group-two-facts-in-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!