如何让 TuProlog 识别无效事实?

How to make TuProlog recognize invalid facts?

我有以下两个 Prolog 文件:

ontology.pl:

isSite(Url) :- string(Url).
guestPostPublished(GuestPostId, Date, Site, Url) :-
 string(GuestPostId),
 date(Date),
 isSite(Site),
 string(Url),
 \+(guestPostPublished(GuestPostId, _, _, _)).

invalidFile.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 必须唯一的规则。

当我将该数据加载到我的引擎中时,我将它抛出一些异常,表明该数据无效。但事实并非如此。

我做错了什么?我如何确保当我向 TuProlog 引擎提供无效数据时,我会收到某种通知(例如异常或某些标志)?

这是我的代码的相关片段(你可以找到完整的代码here):

@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;
}

要对 Prolog table 事实设置数据完整性约束,您需要采用不同的方法。我建议您首先尝试在没有 Java 位的情况下在纯 Prolog 中执行此操作,只是为了了解正在发生的事情。

如果数据库是静态的并且不会改变,这很容易:只需加载它,然后 运行 查询它进行数据完整性检查。例如,您有一个只有一个列的 table site/1,并且您希望确保所有值都是字符串:

There is no site(S) so that S is not a string

\+ ( site(S), \+ string(S) )

如果您想将其包装到一个谓词中,您必须使用与您的 table 不同的名称来命名谓词!

site_must_be_string :-
    \+ ( site(S), \+ string(S) ).

或者,对于另一个,唯一列(主键):

There are no duplicates among the first arguments to guest_post_published/4

findall(ID, guest_post_published(ID, _, _, _), IDs),
length(IDs, Len),
sort(IDs, Sorted),   % sort/2 removes duplicates!
length(Sorted, Len). % length does not change after sorting

您可能也需要将其包装在它自己的谓词中。

如果您想在断言之前检查 "alleged" 个事实的有效性,您会想要阅读而不是查阅该文件并尝试调用每个所谓的事实以查看它是否成功。

作为一个非常简单的示例,您可以执行以下操作:

open('invalidFile.pl', read, S),
read(S, TestFact),
call(TestFact).

如果从 invalidFile.pl 读取的术语根据您现有的事实和规则成功,则 call(TestFact) 将成功,否则它将失败。您可以使用此序列并阅读所有所谓的事实并对其进行测试:

validate_file(File) :-
    open(File, read, S),
    read_terms(S, Terms),
    maplist(call, Terms),   % This will fail if *any* term fails
    close(S).

read_terms(Stream, []):- 
    at_end_of_stream(Stream). 

read_terms(Stream, [Term|Terms]):- 
    \+  at_end_of_stream(Stream), 
    read(Stream, Term), 
    read_terms(Stream, Terms).

在这种情况下,如果文件中的 任何 项为假,validate_file 将失败。作为练习,您可以通过跟踪 "term count" 或 read_terms 中的类似内容来使它更智能,并编写一个谓词来检查术语并在失败时反馈术语编号,以便您可以看到是哪一个(s) 失败。