Node:Dynamic Methods, Next:, Previous:Dynamically Declared Objects, Up:Obj Hierarchies



Dynamic Methods

To be able to change a method with functor F/N in a static object, the method has to be declared dynamic by storing the following fact in the object:

     some_object :: {
             dynamic F/N &
             :
             }.
     

Each book in a library can be represented as an object, in which the name of the book is stored, the authors, and a borrowing history indicating when a book is borrowed and when it is returned. A history item may have the form history_item(Person,Status,Date) where Status is either borrowed or returned, and Date has the form YY-MM-DD, for YY year, MM month, DD day.

A typical book book_12 could have the following status. Note that history_item/3 is dynamic:

     book_12 :: {
             super(book) &
     
             title('The Art of Prolog') &
             authors(['Leon Sterling', 'Ehud Shapiro']) &
     
             dynamic history_item/3 &
     
             history_item('Dan Sahlin', returned, 92-01-10) &
             history_item('Dan Sahlin', borrowed, 91-06-10) &
             :
             }.
     

Dynamic methods that are stored in an object can be updated, as in usual Prolog programs, by sending assert and retract messages directly to the object.

For example, to borrow a book the following method could be defined in the object book. We assume that the top most history_item fact is the latest transaction, and there is an object date from which we can get the current date.

     borrow(Person) :-
             history_item(_Person0, Status, _Date0), !,
             (   Status = returned ->
                 date::current(Date),
                 asserta(history_item(Person, borrowed, Date))
             ;   :display('book not available'), :ttynl
             ) &