man(alan).
man(john).
man(george).
list_all:-
man(X),
write(X),
fail.
问题?-list_all
给出答案:
alan
john
george
false
所以我有来自数据库的所有人。有用!我的问题:我想获得相同的列表,但导出到.txt
文件。我尝试使用此代码执行此操作:
program :-
open('file.txt',write,X),
current_output(CO),
set_output(X),
man(X),
write(X),
fail,
close(X),
set_output(CO).
效果是:由于使用false
谓词,程序会给出答案alan john george
和文字:.txt
不在fail
文件中。
是否可以选择将列表中的所有项目都放入.txt
文件(编写数据库中的所有选项)而不使用fail
谓词?
我该怎么做?请帮帮我。
答案 0 :(得分:6)
你快到了。但是对fail/0
的调用会阻止关闭流。试试例如:
program :-
open('file.txt',write, Stream),
( man(Man), write(Stream, Man), fail
; true
),
close(Stream).
使用事实上的标准forall/2
谓词的替代方法可能是:
program :-
open('file.txt',write, Stream),
forall(man(Man), write(Stream,Man)),
close(Stream).
,,,