在序言中读取文件并构造事实 [英] read file and construct facts in prolog

查看:46
本文介绍了在序言中读取文件并构造事实的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一种机制,根据txt文件构建不同的事实,在序言中导入.我已经找到了一些直接断言从文件中读取的行的示例,但我必须在断言发生之前转换数据.

I would like to construct a mechanism that constructs different facts depending from txt file, imported in prolog. I already have found some examples where they directly assert the line that was read from the file, but I have to transform the data before assertion can take place.

举个例子:

man = {m1, m2}.

m1: w1 > w2.

应读作:

man(m1).
man(m2).
prefer(m1, w1, 1).
prefer(m1, w2, 2).

是否可以根据输入的符号来构造这些事实?

Is it possible to construct these facts based on the symbols of the input?

推荐答案

由于示例中提供的数据是有效的 Prolog 语法这一事实,此代码将执行

thanks to the fact that data presented in example is valid Prolog syntax, this code will do

load_file_data(File) :-
    open(File, read, Stream),
    repeat,
    read(Stream, Term),
    (   Term = end_of_file
    ->  true
    ;   process(Term),
        fail
    ),
    close(Stream).

process(X = {L}) :-
    forall(arg(_, L, A), (F =.. [X, A], assert(F))).
process(X : A > B) :-
    assert(prefer(X, A, 1)),
    assert(prefer(X, B, 2)).

注意m1中运算符的优先级:w1>w2 不是我们所期望的,但由于完整的模式匹配,它无论如何都可以工作.使用

note that the precedence of operators in m1: w1 > w2 is not what we could expect, but it works anyway, thanks to complete pattern matching. Use

?- write_canonical(m1 : w1 > w2).
>(:(m1,w1),w2)

不确定时检查优先级.

这篇关于在序言中读取文件并构造事实的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆