使用 Prolog 返回整数 [英] Return Integer with Prolog

查看:17
本文介绍了使用 Prolog 返回整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在试着理解序言.我想给出输入: convert(s(s(s(X))),Y) 输出应该是 Y = 3.

I try to understand prolog right now. I want to give the input: convert(s(s(s(X))),Y) and the output should be Y = 3.

convert(s(0), 1).
convert(s(s(0)), 2).
convert(s(X),Y) :- convert(X,Y is (Y+1)).

这些是我现在的规则,但只有输入:convert(s(0), 1).和转换(s(s(0)), 2).工作.

Those are my rules right now, but only the inputs: convert(s(0), 1). And convert(s(s(0)), 2). work.

如果我的递归可以正常工作,我就不需要规则:convert(s(s(0)), 2).有人可以帮我解决这个问题吗?

If my recursion would work right, I wouldn't need the rule: convert(s(s(0)), 2). Can someone help me with that problem?

推荐答案

这里有两个问题:

  • Y 是 Y+1,在 Prolog 中没有任何意义;和
  • 请注意,您实际上已经写了一个函子.
  • Y is Y+1, does not makes any sense in Prolog; and
  • note that you here actually have written a functor.

Prolog 认为这是一个调用:

Prolog sees this as a call:

convert(X,is(Y,Y+1))

is(Y,Y+1) 被调用,而是作为函子传递.在 Prolog 中没有明确的输入和输出.你调用谓词,通过统一,你得到结果.

where is(Y,Y+1) is not called, but passed as a functor. In Prolog there is no clear input and output. You call predicates and through unification, you obtain results.

然而我们可以通过递归来解决这个问题:0convert/2当然是0:

We can however solve the problem by using recursion: the convert/2 of 0 is of course 0:

convert(0,0).

和一个s(X)的转换,是X的转换加一:

and the convert of an s(X), is the convert of X plus one:

convert(s(X),R) :-
    convert(X,Y),
    R is Y+1.

或者把这些放在一起:

convert(0,0).
convert(s(X),R) :-
    convert(X,Y),
    R is Y+1.

现在我们可以调用谓词列出所有 Peano 数字和对应的数字,以及将 Peano 数字转换为数字.我们还可以验证 Peano 数是否为正常数.

Now we can call the predicate to list all Peano numbers and the corresponding number, as well as converting a Peano number into a number. We can also validate if a Peano number is a normal number.

不幸的是,我们不能使用这个谓词从给定的数字中获取 Peano 数:它将与 Peano 数合一,但在尝试寻找另一个 Peano 数时,会陷入无限循环.

Unfortunately we can not use this predicate to obtain the Peano number from a given number: it will unify with the Peano number, but in a attempt to look for another Peano number, will get stuck into an infinite loop.

我们可以使用 clpfd 库来帮助我们:

We can use the clpfd library to help us with this:

:- use_module(library(clpfd)).

convert(0,0).
convert(s(X),R) :-
    R #> 0,
    Y #= R-1,
    convert(X,Y).

这篇关于使用 Prolog 返回整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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