Prolog加法练习(Prolog addition excercise)

编程入门 行业动态 更新时间:2024-10-26 00:23:59
Prolog加法练习(Prolog addition excercise)

我有这个非常简单的代码作为数字的表示。 问题是当我使用add2函数时。

示例: add2(s(0)+s(s(0)), s(s(0)), Z). 正确地返回s(s(s(s(s(0))))) 。 但是add2(0, s(0)+s(s(0)), Z). 总是returns s(0)+s(s(0)) 。 有人能看出为什么会这样吗?

numeral(0). numeral(s(X)) :- numeral(X). numeral(X+Y) :- numeral(X), numeral(Y). add(0,X,X). add(s(X),Y,s(Z)) :- add(X,Y,Z). %% exercise 1 add2(X,Y,R) :- add(X,Y,R). add2(X+Y,Z,R) :- add(X,Y,A),add2(A,Z,R). add2(X,Y+Z,R) :- add(Y,Z,A),add2(X,A,R).

I have this very simple code as a representation of numerals. The problem is when I use the add2 function.

Example: add2(s(0)+s(s(0)), s(s(0)), Z). returns s(s(s(s(s(0))))) correctly. However add2(0, s(0)+s(s(0)), Z). always returns s(0)+s(s(0)). Can anyone see why this is happening?

numeral(0). numeral(s(X)) :- numeral(X). numeral(X+Y) :- numeral(X), numeral(Y). add(0,X,X). add(s(X),Y,s(Z)) :- add(X,Y,Z). %% exercise 1 add2(X,Y,R) :- add(X,Y,R). add2(X+Y,Z,R) :- add(X,Y,A),add2(A,Z,R). add2(X,Y+Z,R) :- add(Y,Z,A),add2(X,A,R).

最满意答案

这是因为第一个add2子句和第一个add子句的组合。 你的add2(0, ..., ...)将触发add(0, ..., ...) ,它总是统一第二个和第三个参数。

It's happening because of the combination of the first add2 clause and the first add clause. Your add2(0, ..., ...) will trigger add(0, ..., ...) which always unifies the second and third argument.

更多推荐

本文发布于:2023-08-07 13:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464896.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加法   Prolog   excercise   addition

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!