在 Prolog 中将 peano 数 s(N) 转换为整数 [英] Convert peano number s(N) to integer in Prolog

查看:15
本文介绍了在 Prolog 中将 peano 数 s(N) 转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在教程中遇到了这种逻辑数的自然数评估,这让我有些头疼:

I came across this natural number evaluation of logical numbers in a tutorial and it's been giving me some headache:

natural_number(0).
natural_number(s(N)) :- natural_number(N).

规则大致规定:如果 N0 这是很自然的,如果不是我们尝试将 s/1 的内容发回递归到规则直到内容为0,则为自然数,否则为非自然数.

The rule roughly states that: if N is 0 it's natural, if not we try to send the contents of s/1 back recursively to the rule until the content is 0, then it's a natural number if not then it's not.

所以我测试了上面的逻辑实现,心想,如果我想将 s(0) 表示为 1s(s(0))2,但我希望能够将 s(0) 转换为 1.

So I tested the above logic implementation, thought to myself, well this works if I want to represent s(0) as 1 and s(s(0)) as 2, but I´d like to be able to convert s(0) to 1 instead.

我已经想到了基本规则:

I´ve thought of the base rule:

sToInt(0,0). %sToInt(X,Y) Where X=s(N) and Y=integer of X

这是我的问题:如何将 s(0) 转换为 1 并将 s(s(0)) 转换为 2?

So here is my question: How can I convert s(0) to 1 and s(s(0)) to 2?

已答复

我修改了实现中的基本规则,我接受的答案指向我:

I modified the base rule in the implementation which the answer I accepted pointed me towards:

decode(0,0). %was orignally decode(z,0).
decode(s(N),D):- decode(N,E), D is E +1.

encode(0,0). %was orignally encode(0,z).
encode(D,s(N)):- D > 0, E is D-1, encode(E,N).

所以我现在可以随心所欲地使用它了,谢谢大家!

So I can now use it like I wanted to, thanks everyone!

推荐答案

这是另一个使用 library(clpfd) 的 SWI、YAP 或 SICStus

Here is another solution that works "both ways" using library(clpfd) of SWI, YAP, or SICStus

:- use_module(library(clpfd)).

natsx_int(0, 0).
natsx_int(s(N), I1) :-
   I1 #> 0,
   I2 #= I1 - 1,
   natsx_int(N, I2).

这篇关于在 Prolog 中将 peano 数 s(N) 转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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