read file and construct facts in prolog

后端 未结 3 746
北荒
北荒 2021-01-23 00:34

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

3条回答
  •  离开以前
    2021-01-23 01:09

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

    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)
    

    to check precedence when not sure.

提交回复
热议问题