有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何让TuProlog识别无效事实?

我有以下两个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必须唯一的规则

当我将该数据加载到引擎中时,我会将其删除,以引发一些异常,指示数据无效。但事实并非如此

我做错了什么?我如何确保当我向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;
}

共 (2) 个答案

  1. # 1 楼答案

    要在Prolog事实表上设置数据完整性约束,需要采用不同的方法。我建议您首先尝试使用纯Prolog,不使用Java位,只是为了了解正在发生的事情

    如果数据库是静态的,并且没有更改,那么就很容易了:只需加载它,然后对其运行查询以进行数据完整性检查。例如,您有一个表site/1,其中只有一列,您希望确保所有值都是字符串:

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

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

    如果要将其包装为谓词,必须使用与表不同的名称命名谓词

    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
    

    你可能也需要用它自己的谓词来概括它

  2. # 2 楼答案

    如果你想在断言之前检查“声称”事实的有效性,你应该阅读文件,而不是查阅文件,并尝试调用每个声称的事实,看看它是否成功

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

    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).
    

    在这种情况下,如果文件中的任何项为false,validate_file将失败。作为练习,您可以通过跟踪read_terms中的“术语计数”或类似内容,编写一个谓词来检查一个术语,并在其失败时反馈术语编号,这样您就可以看到哪个(s)失败了