【问题标题】:How to write in a file N times in Prolog?如何在Prolog中写入文件N次?
【发布时间】:2022-11-14 04:57:37
【问题描述】:

我正在尝试在 Prolog 中写入 N 次文件。我想出了这个解决方案:

response(M,Out,N):-
write('How do you feel ?'),
open('output.txt',write,Out),
read(M),
write(Out,M),
close(Out),
response(M,Out,S),
S is N-1.


response(M,Out,0).

基本思想是从键盘读取情绪并将其写入名为output.txt 的文件中。它给了我这个错误:

ERROR: Uninstantiated argument expected, found <stream>(0x60000311fb00) (stream-argument)
ERROR: In:
ERROR:   [12] open('/Users/dylan/Desktop/output.txt',write,<stream>(0x60000311fb00))
ERROR:   [11] response(sad,<stream>(0x60000311fb00),_10234) at /Users/dylan/Desktop/suggestsong.pl:14
ERROR:   [10] response(sad,<stream>(0x60000311fb00),3) at /Users/dylan/Desktop/suggestsong.pl:18
ERROR:    [9] toplevel_call(user:user: ...) at /Applications/SWI-   Prolog.app/Contents/swipl/boot/toplevel.pl:1158
Exception: (11) response(sad, <stream>(0x60000311fb00), _9654) ? creep
Exception: (10) response(_9306, _9308, 3) ? creep

没有循环的谓词工作正常,但它只是一次阅读,不适合目的。

可以请人帮助我吗?谢谢你们。

【问题讨论】:

标签: prolog


【解决方案1】:

要执行文件写入:

append_file_output(File, Output) :-
    setup_call_cleanup(
        open(File, append, Stream),
        writeln(Stream, Output),
        close(Stream)
    ).

结果 swi-prolog:

?- append_file_output('test.txt', woo).
true.

?- append_file_output('test.txt', hoo2).
true.
$ cat test.txt
woo
hoo2

【讨论】:

    【解决方案2】:

    感谢您的解决方案!

    我实际上还找到了另一种简单的方法来解决这个问题,使用递归:

    % chat with user 
    chat :-
      ask("y").
    
    
    ask("y") :-
       write('How do you feel?: '),
       read_string(user, "
    ", "
    ", End, E),
       %assert(emotion(E)), %assert a fact or rule into database
       suggest(emotion(E)),
       write("Continue: (y or n) "),
       read_string(user, "
    ", "
    ", End, Respond),
       ask(Respond).
    
    
    % The user type "n", hence computing and writing results into file
    ask("n") :- 
      tell('output.txt'), 
      %listing(emotion/1), 
      listing(genre/2),  %lookup result of genre/2 into database
      told.
    

    【讨论】:

      猜你喜欢
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      相关资源
      最近更新 更多