Rule to group two facts in prolog?

2019-07-28 17:57发布

问题:

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



标签: prolog rules