is 和 = 有什么区别? [英] What is the difference between is and =?

查看:128
本文介绍了is 和 = 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将这些语句输入到 prolog 解释器中,但对结果感到困惑.他们不应该返回同样的东西吗?真的吗?

I have entered these statements into the prolog interpreter and am confused by the results. Shouldn't they return the same thing; true?

1 ?- 7 = 5 + 2.
false.

2 ?- 7 is 5 + 2.
true.

推荐答案

否,因为 =/2 在 Prolog 中并不意味着 assign,而是 unify.统一算法对算术一无所知,只知道结构.所以你可以用 Prolog 中的算术表达式做一些在其他语言中很难做到的有趣的事情:

No, because =/2 does not mean assign in Prolog, but rather unify. And the unification algorithm does not know anything at all about arithmetic, just structure. So you can do some interesting things with arithmetic expressions in Prolog that are quite difficult to pull off in other languages:

?- X = 5 + 2.
X = 5+2.

看起来那里什么也没发生,但实际发生的是 X 被赋予了值5 + 2"作为一个结构.换一种方式:

It looks like nothing happened there, but what actually happened is X was given the value "5 + 2" as a structure. Put another way:

?- A + B = 5 + 2.
A = 5,
B = 2.

甚至:

?- X = 5 + 2, X =.. [Op|_]. 
X = 5+2,
Op = (+).

不过,最后一个可能对整个列表更有意义:

That last one might make more sense with the whole list though:

?- X = 5 + 2, X =.. Y.
X = 5+2,
Y = [+, 5, 2].

这是非凡的univ"运算符的效果,=../2,它能够在类似 Lisp 的列表和 Prolog 语法之间进行转换,使您能够进行有趣的构造和分解以通用方式的结构.

This is an effect of the remarkable "univ" operator, =../2, which is able to convert between Lisp-like lists and Prolog syntax, enabling you to do interesting construction and decomposition of structures in a generic fashion.

现在,is/2,另一方面,确实了解算术.它将其左边的参数与其右边的算术简化结果统一起来.请注意它只能在一个方向上起作用:

Now, is/2, on the other hand, does know about arithmetic. It unifies its left argument with the result of arithmetic simplification of its right. Do note that it only works in one direction:

?- 7 is 5 + 2.
true.

?- 5 + 2 is 7.
false.

你可以说 =/2 对结构感兴趣,而 is/2 对数字相等感兴趣.但这确实意味着教授 Prolog 代数非常容易:

You could say that =/2 is interested in structure and is/2 is interested in numeric equality. But it does mean that it's unusually easy to teach Prolog algebra:

simplify(X * Y + X * Z, X * (Y + Z)).  % distributive property
simplify(X, X).

?- simplify(A * 3 + A * 4, Q).
Q = A* (3+4)

现在,这并不完美(请注意,我们得到的是 3+4 而不是 7),要让它变得真正智能还有很多工作要做:

Now, this isn't perfect (note that we got 3+4 and not 7) and it's still a lot of work to make it really smart:

?- simplify(3 * A + 4 * A, Q).
Q = 3*A+4*A.

但这是另一天的问题.

简而言之:

  • =/2 触发统一
  • is/2 触发算术求值
  • =/2 triggers unification
  • is/2 triggers arithmetic evaluation

这篇关于is 和 = 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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