如何打印出序言中的所有事实 [英] How to print out all the facts in prolog

查看:41
本文介绍了如何打印出序言中的所有事实的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一套规则和一个函数,可以打印出所有动物,如下所示.

I have a set of rules and a function which prints out all the animals as follows.

animal(dog).
animal(cat).
animal(rat).

printAnimals :-
  animal(X),
  format("~q",[X]).

在终端中,当我输入 printAnimals. 我只得到狗.cat 和 rat 仅在我按下 ; 按钮时才会打印.我如何修改此功能以打印出所有动物而无需按 ;.

In the terminal when i type out printAnimals. I only get dog. cat and rat only get printed when i press the ; button. How do i modify this function to print out all the animals without having to press ;.

推荐答案

在您的方法中,回溯是交互式的,通过按下 ; 在 REPL(Prolog 顶层)发生.

In your approach, backtracking is interactive and occurs at the REPL (the Prolog toplevel) by pressing ;.

您必须使用元谓词之一收集所有动物

You have to collect all the animals either by using one of the meta-predicates

创建一个动物列表,然后可以使用<代码>maplist/2.

to create a list of animals which can then be printed using maplist/2.

您也可以使用 forall/2 在收集动物时产生副作用.

You can also use forall/2 to emit side-effects as animals are collected.

或者你可以写一个失败驱动的循环:

Or you can write a failure-driven loop:

printAllAnimals :-
  animal(X),
  format("~q",[X]),
  fail. % failure causes backtracking to animal(X), which collects the next animal

这篇关于如何打印出序言中的所有事实的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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