Writing in file | Swi-Prolog | Windows

2019-02-26 03:41发布

Some script is working successful by swi-prolog 5.11.11 on linux-system, but not so well on windows-system by Swi-Prolog 5.6.48

main :-
    open('output.txt',write,OS),
    elements(Points),
    get_set(Eq, Points),
    alpha_isotone(Eq, Points),
    write(OS,Eq),nl(OS),
    false,
    close(OS).

Problem - under the windows file output.txt is empty and all information is staying in pseudo-terminal. Under linux it's working well, but end of file is missed often. Like

>> tail output.txt      
[6,1,3,6,6,6]
[6,1,6,6,6,6]
[6,3,1,6,6,6]
[6,3,3,6,3,6]
[6,3,3,6,5,6]
[6,3,3,6,6,6]
[6,3,6,6,6,6]
[6,6,1,6,6,6]
[6,6,3,6,6,6]
[6,6,6,

What am I doing wrong? (except of my english)

标签: prolog
2条回答
仙女界的扛把子
2楼-- · 2019-02-26 04:04

If one wanted to keep the close(OS) within a "single" main/0 clause, this also works:

main :-
    open('output.txt',write,OS),
    (   elements(Points),
        get_set(Eq, Points),
        alpha_isotone(Eq, Points),
        write(OS,Eq),nl(OS),
        false
        ;
        close(OS)
    ).

This syntax is not recommended as it is hard to remember what is the precedence of the conjunction , versus disjunction ; unless you frequently use such coding, and it is on that account less readable than the version presented by larsmans.

Prolog defines the relative precedence of operators, even for AND, OR, and "neck" :-, by assigning Precedence values to each (users do this with op/3 when defining their own operators), ranging from 0 to 1200.

There is also a reversal of the usual convention here, in that we normally mean the higher precedence operator is to be applied before lower precedence operators. But in Prolog the lower Precedence value indicates an operator binds (is applied) first.

Actual precedence values vary with the implementation, but conjunction , has lower Precedence value than disjunction ; and thus binds first.

查看更多
Melony?
3楼-- · 2019-02-26 04:15

I'm assuming this was meant to be a failure-driven loop. It doesn't work because the close/1 call, as @hardmath says, is never reached since it is preceded by a fail/1 in the same clause. In effect, the output file is apparently not flushed. This failure-driven loop should be written as:

main :-
    open('output.txt', write, OS),
    main(OS).

main(OS) :-
    elements(Points),
    get_set(Eq, Points),
    alpha_isotone(Eq, Points),
    write(OS,Eq), nl(OS),
    false.
main(OS) :- close(OS).
查看更多
登录 后发表回答