1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| :- op(600, xfy, ::). % send message to object
% use '::' operator as syntax for send message
Object::Message :-
send(Object, Message).
% send(Message, Object): find Object's method and execute
send(Object, Message) :-
get_methods(Object, Methods), % Find Object's methods
process(Message, Methods). % Execute corresponding method
% get the defined methods for the class
get_methods(Object, Methods) :- % Private methods
object(Object, Methods).
% get the defined methods inherited from the superclass
get_methods(Object, Methods) :- % Inherited methods
isa(Object, SuperObject),
get_methods(SuperObject, Methods).
% process the method if it is defined as a fact
process(Message, [Message | _]) :- % Use a fact
process(Message, [Message | _]).
% process the method if it is defined as a rule
process(Message, [(Message :- Body) | _]) :- % Use a rule
call(Body).
process(Message, [_ | Methods]) :- % break the message up
process(Message, Methods).
object(
shape(X, Y), [
(getx(X) :- X is X),
(gety(Y) :- Y is Y)
]
).
object(
rectangle(Width, Height), [
(getwidth(W) :-
W is Width),
(getheight(H) :-
H is Height),
(setwidth(NewRectangle, NewWidth) :-
NewRectangle = rectangle(NewWidth, Height)),
(setheight(NewRectangle, NewHeight) :-
NewRectangle = rectangle(Width, NewHeight)),
(print :-
write('Drawing a Rectangle ('),
write(Width),
write('*'),
write(Height),
write(')'),
nl)
]
).
isa(rectangle(WIDTH, HEIGHT), shape(WIDTH, HEIGHT)). |
Partager