| | 58 | <p> |
| | 59 | A more complicated scenario is when you have several files containing clauses for a multifile predicate. For example, assume that a multifile predicate named <code>mp/2</code> is defined in two files. In this case, start by defining a protocol containing the declaration of the multifile predicate: |
| | 60 | </p> |
| | 61 | <pre> |
| | 62 | :- protocol(ptc). |
| | 63 | |
| | 64 | :- public(mp/1). |
| | 65 | |
| | 66 | :- end_protocol. |
| | 67 | </pre> |
| | 68 | <p> |
| | 69 | Second, for each file, define a category containing the corresponding clauses for the <code>mp/2</code> predicate: |
| | 70 | </p> |
| | 71 | <pre> |
| | 72 | :- category(ctg1, |
| | 73 | implements(ptc)). |
| | 74 | |
| | 75 | mp(1). % clauses from the first file |
| | 76 | mp(2). |
| | 77 | |
| | 78 | :- end_category. |
| | 79 | |
| | 80 | |
| | 81 | :- category(ctg2, |
| | 82 | implements(ptc)). |
| | 83 | |
| | 84 | mp(3). % clauses from the first file |
| | 85 | mp(4). |
| | 86 | |
| | 87 | :- end_category. |
| | 88 | </pre> |
| | 89 | <p> |
| | 90 | Next, define an object importing all the categories and defining aliases to the imported predicates: |
| | 91 | </p> |
| | 92 | <pre> |
| | 93 | :- object(obj, |
| | 94 | implements(ptc), |
| | 95 | imports(ctg1, ctg2)). |
| | 96 | |
| | 97 | :- alias(ctg1, mp/1, ctg1_mp/1). |
| | 98 | :- alias(ctg2, mp/1, ctg2_mp/1). |
| | 99 | |
| | 100 | mp(X) :- |
| | 101 | ::ctg1_mp(X). |
| | 102 | mp(X) :- |
| | 103 | ::ctg2_mp(X). |
| | 104 | |
| | 105 | :- end_ object. |
| | 106 | </pre> |
| | 107 | <p> |
| | 108 | The predicate aliases above are needed to allow access to the overridded clauses of the <code>mp/1</code> predicate (by default, the clauses from <code>ctg1</code> would override the clauses from the <code>ctg2</code> category as a consequence of the predicate lookup mechanism). |
| | 109 | </p> |
| | 110 | <p> |
| | 111 | Compiling and loading the above Logtalk entities allows you to access all clauses of the former multifile predicate. For example: |
| | 112 | </p> |
| | 113 | <pre> |
| | 114 | | ?- obj::mp(X). |
| | 115 | |
| | 116 | X = 1 ; |
| | 117 | X = 2 ; |
| | 118 | X = 3 ; |
| | 119 | X = 4 |
| | 120 | yes |
| | 121 | </pre> |