0

I have written a decimal floating point unit for LaTeX3 (pure macros... that was tough). In particular, I have to decide how x < y < z should be parsed. I see three options:

  • Treat < as a left-associative binary operator, so x < y < z would be equivalent to (x < y) < z. This is what C does: -1 < 0 < 1 becomes (-1 < 0) < 1, thus 1 < 1, which is 0.

  • Treat < as a right-associative binary operator, so x<y<z would be equivalent to x < (y < z). I see no advantage to that option.

  • When encountering <, read ahead for more comparison operators, and treat x < y < z as equivalent to (x < y) && (y < z), where y would be evaluated only once. This is what most non-programmers would expect. And quite a few LaTeX users are non-programmers.

At the moment I am using the first option, but it does not seem very natural. I think that I can implement the second case whithout too much overhead. Should I?

Since that question is subjective, let me ask an objective question: what mainstream languages pick option 3? I'm interested in the details of what happens with mixed things like a < b > c == d < e != f. I'm also interested in other choices if they exist.

4

3 回答 3

3

简短的回答:只有当比较序列“指向同一个方向”并且你不使用!=.

长答案:在 Python 中,3 > 2 > 1计算结果为True. 但是,我不得不说使用的实现过于简单化,因为它允许像这样的表达式a < b > c == d < e != f,在我看来这是无意义的。该表达式将被解释为 (a < b) and (b > c) and (c == d) and (d < e) and (e != f)。这是一个简单的规则,但因为它允许令人惊讶的结果,我不喜欢这种解释。

我提出了一个更可预测的选择:

  • 考虑一个命题xAyBzCw。如果这个命题是“有道理的”,它等价于xAy and yBz and zCw。对于“感性”,有必要...

    • 值 ( x, y, z, w) 是同一集合的一部分X(或者它们的类型可以这样统一),并且
    • 关系(A , B, C) ,和X
    • 对于每对有序的关系AB,都存在一个关系,CxAy and yBz意味着xCz, x, y; z这种关系也受到这些限制。

关于最后一条规则,您希望能够说 that1 < 2 = a < 4等价于1<2 and 2=a and a<4,但也可以说1<2 and 1<a and 1<4. 要说后者,你必须知道如何=互动<

你不能!=在我的选项中使用,因为它不是传递的。但是你也不能说1 < 3 > 2, 2 < 3 > 1, or 1 < 3 > 1, 除非你有一个?这样的关系1?2, 2?1and 1?1(基本上,这将是一个允许任何对的关系)。

从句法的角度来看:您希望将关系运算符视为特殊运算符(+更像是函数运算符),有点像您的第三个选项。

于 2012-08-23T14:11:27.600 回答
2

J从右到左评估语句,以便:

3 > 2 > 1

成为第一

2 > 1

解析为真,表示为 1,因此:

3 > 1

这也解析为真,因此为 1。相反的运算符<将导致错误,而整个语句恰好为真。所以你不再和 J 在一起了。

您的主要问题是您的初始代表:

3 > 2 > 1

是人类的简写

(3 > 2) AND (2 > 1)

因此,虽然提前阅读似乎很讨厌,但这确实是表示所需要的。除非当然有一些 Python 魔法,正如其他人所说的那样。

于 2012-08-23T14:29:15.080 回答
2

Python 链关系运算符。in当您点击and时,这会变得很有趣is,因为它们也被认为是关系型的。

>>> 1 < 2 in [True, False]
False
>>> 1 < 2 in [2, 4]
True
于 2012-08-23T13:23:46.913 回答