Prolog - 如何将所有 prolog 答案写入 .txt 文件? [英] Prolog - How to write all prolog answers to .txt file?

查看:22
本文介绍了Prolog - 如何将所有 prolog 答案写入 .txt 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人(艾伦).男人(约翰).人(乔治).list_all:-男人(X),写(X),失败.

问题 ?-list_all 给出了答案:

艾伦约翰乔治错误的

所以我有数据库中的所有男人.有用!我的问题:我想获得相同的列表,但导出到 .txt 文件.我尝试使用此代码来执行此操作:

程序:-open('file.txt',write,X),当前_输出(CO),设置输出(X),男人(X),写(X),失败,关闭(X),设置输出(CO).

效果是:程序给出答案 false 和文本:alan john george 不在 .txt 文件中 - 因为使用了 fail 谓词.

是否可以在不使用 fail 谓词的情况下将列表中的所有项目放入 .txt 文件(写入数据库中的所有选项)?>

我该怎么做?请帮帮我.

解决方案

大功告成.但是对 fail/0 的调用会阻止流被关闭.尝试例如:

程序:-open('file.txt',write, Stream),(人(人),写(流,人),失败;真的),关闭(流).

使用事实上的标准 forall/2 谓词的替代方法可能是:

程序:-open('file.txt',write, Stream),forall(人(人),写(流,人)),关闭(流).

, , ,

man(alan).
man(john).
man(george).

list_all:-
  man(X),
  write(X),
  fail.

Question ?-list_all gives the answer:

alan
john
george
false

So I have all the men from the database. It works! My problem: I want to get the same list, but exported to .txt file. I tried to use this code to do this:

program  :-
  open('file.txt',write,X),
  current_output(CO),
  set_output(X),
  man(X),
  write(X),
  fail,
  close(X),
  set_output(CO).

The effect is: Program gives answer false and text: alan john george are not in .txt file - because of using fail predicate.

Is there an option to get all the items in the list into a .txt file (writing all options which are in database) without using fail predicate?

How can I do this? Please help me.

解决方案

You're almost there. But the call to fail/0 prevents the stream to be closed. Try for example:

program :-
    open('file.txt',write, Stream),
    (   man(Man), write(Stream, Man), fail
    ;   true
    ),
    close(Stream).

An alternative using the de facto standard forall/2 predicate could be:

program :-
    open('file.txt',write, Stream),
    forall(man(Man), write(Stream,Man)),
    close(Stream).

, , ,

这篇关于Prolog - 如何将所有 prolog 答案写入 .txt 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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