0
votes

I'm new to writing Prolog and would like to know how to state the following properties in a way that's useful for later reasoning.

  • There are N objects.
  • Every object has a color.
  • There are three possible colors: red, green, blue

Let's assume there are two objects: object 1 is red, object 2 has a different, unspecified color. How can I ask Prolog for possible colors of object 2? I'd expect green and blue.

My code so far:

object(obj_1).
object(obj_2).

color_value(red).
color_value(green).
color_value(blue).

color(Obj, Val) :- object(Obj), color_value(Val).
color(obj_1, red).

different_color(O1, O2) :- color(O1, X), color(O2, Y), X \= Y.
different_color(obj_1, obj_2).

When I query for possible colors of obj_2, Prolog includes red. So I'm doing it wrong somehow.

color(obj_2, A).
A = red ;
A = green ;
A = blue.

I suspect there's something wrong with how I use color and different_color.

1
Stylewise, color(Obj, Val) :- object(Obj), color_value(Val). is a kind of typing. You really don't need it in this setting. Worse, it interferes with setting up the facts about "object - color" relationship. Because when you ask "does obj_1 have color green", Prolog will find color(Obj, Val) :- object(Obj), color_value(Val). and say yes because obj_1 is an object, and green is a color. Whereas you really want to say "the color of obj_1 is red and no other color": color(obj_1, red).David Tonhofer

1 Answers

2
votes

Your definition of color/1 offers redundant solutions for color(_, red) or color(obj_1, _). Your clause for color(Obj, Val) needs to exclude the case where Obj is obj_1 or Val is red.

A simplistic approach could be:

color(Obj, Val) :-
    dif(Obj, obj_1),
    dif(Val, red),
    object(Obj),
    color_value(Val).
color(obj_1, red).

Also, consider @DavidTonhofer's comment about style. :)