我有以下两个 Prolog 文件:
本体.pl:
isSite(Url) :- string(Url).
guestPostPublished(GuestPostId, Date, Site, Url) :-
string(GuestPostId),
date(Date),
isSite(Site),
string(Url),
\+(guestPostPublished(GuestPostId, _, _, _)).
无效文件.pl:
isSite('somesite.com').
guestPostPublished(
'gp1',
date(2016,2,2),
'somesite.com',
'someUrl').
guestPostPublished(
'gp1',
date(2016,2,2),
'somesite.com',
'anotherUrl').
invalidFile.pl
是无效的,因为它违反了ontology.pl
所有GuestPostId
s 必须是唯一的规则。
当我将该数据加载到我的引擎中时,我除了抛出一些异常,表明数据无效。但事实并非如此。
我究竟做错了什么?如何确保当我向TuProlog引擎提供无效数据时,我会收到某种通知(例如异常或某些标志)?
这是我的代码的相关片段(您可以在此处找到整个代码):
@Test
public void test2() throws InvalidObjectIdException, IOException,
MalformedGoalException, InvalidTheoryException, UnknownVarException, NoSolutionException,
NoMoreSolutionException, InvalidLibraryException {
final Prolog engine = createEngine();
try
{
loadPrologFiles(engine, new String[]{
"src/main/resources/ontology.pl",
"src/main/resources/invalidFile.pl"
});
Assert.fail("Engine swallows invalid Prolog file.");
}
catch (final Exception exception) {
// TODO: Check that the right exception is thrown
}
final List<String> result = getResults(engine, "guestPostPublished(_,X,_,_).", "X");
System.out.println("result: " + result);
}
private Prolog createEngine() throws InvalidObjectIdException {
final Prolog engine = new Prolog();
engine.addOutputListener(new OutputListener() {
public void onOutput(OutputEvent outputEvent) {
System.out.println(String.format("PROLOG: %s", outputEvent.getMsg()));
}
});
Library lib = engine.getLibrary("alice.tuprolog.lib.OOLibrary");
((OOLibrary)lib).register(new Struct("stdout"), System.out);
return engine;
}
private void loadPrologFiles(final Prolog engine, final String[] files) throws IOException, InvalidTheoryException {
final List<String> paths = Arrays.asList(files);
final StringBuilder theoryBuilder = new StringBuilder();
for (final String path : paths) {
theoryBuilder.append(System.lineSeparator());
theoryBuilder.append("% ");
theoryBuilder.append(path);
theoryBuilder.append(" (START)");
theoryBuilder.append(System.lineSeparator());
theoryBuilder.append(FileUtils.readFileToString(new File(path)));
theoryBuilder.append(System.lineSeparator());
theoryBuilder.append("% ");
theoryBuilder.append(path);
theoryBuilder.append(" (END)");
theoryBuilder.append(System.lineSeparator());
}
final Theory test1 = new Theory(theoryBuilder.toString());
engine.setTheory(test1);
}
private List<String> getResults(final Prolog engine, final String query, final String varName) throws
MalformedGoalException, NoSolutionException, UnknownVarException, NoMoreSolutionException {
SolveInfo res2 = engine.solve(query);
final List<String> result = new LinkedList<String>();
if (res2.isSuccess()) {
result.add(res2.getTerm(varName).toString());
while (engine.hasOpenAlternatives()) {
res2 = engine.solveNext();
final Term x2 = res2.getTerm("X");
result.add(x2.toString());
}
}
return result;
}