如何在Prolog中使用回溯来无限增加变量

如何在Prolog中使用回溯来无限增加变量

本文介绍了如何在Prolog中使用回溯来无限增加变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我目前正在阅读一本Prolog书籍,并且被困在其中一项挑战练习中.我打算用一个参数创建一个谓词.当此参数为变量时,它将返回以下内容并进行回溯,并且X将继续无限制地递增.

I am currently reading a Prolog book and I am stuck on one of the challenge exercises. I am meant to create a predicate with one argument. When this argument is a variable, it will return the following with backtracking, and X will continue to increment with no limit.

X = 0,X = 1,X = 2,X = 3,X = ...

X = 0, X = 1, X = 2, X = 3, X = ...

我做了一个简单的谓词,在该谓词下回溯了0-2,但我想不出一种使它无限继续的方法.

I made the simple predicate below which backtracks through 0-2 but I can't figure out a way to make it continue infinitely.

backtracking_exercise(X) :-
    X = 0;
    X = 1;
    X = 2.

我正在考虑使用between/3谓词,但这只会给出有限数量的数字.我还尝试了plus/3谓词和递归,但是没有运气.这是我想出的,但是正如您所知,它目前没有用.

I was considering using the between/3 predicate but this would be only give a finite amount of numbers. I also experimented with the plus/3 predicate and recursion but no luck. This is what I have come up with, but as you can tell it is currently useless.

backtracking_excercise2(X) :-
    X = 0,
    plus(X,1,Y),
    backtracking_excercise2(Y).

任何有关继续操作的技巧将不胜感激.

Any tips on how to proceed would be greatly appreciated.

先谢谢您.

推荐答案

Jim解决方案的尾部递归变体:

A tail-recursive variant of Jim's solution:

plus(N) :-
    next_integer(1, N).

next_integer(I, I).
next_integer(I, K) :-
    J is I + 1,
    next_integer(J, K).

为防止在使用实例化参数调用plus/1谓词时进入无限循环,即使谓词仅是生成器,可以将第一个子句修改为:

To prevent going into an infinite loop when the plus/1 predicate is called with an instantiated argument, i.e. to make the predicate be only a generator, the first clause can be modified to:

plus(N) :-
    var(N),
    next_integer(1, N).

这篇关于如何在Prolog中使用回溯来无限增加变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:32