为何将ReferenceEquals(x,y)与x==y关联?Zero变量含义解析
Great questions about this implementation of natural number comparisons! Let's break down each one clearly:
1. What is the meaning of the Zero variable, and how is it initialized?
The Zero variable here represents the zero value instance of the Natural type—this is the object that corresponds to the number 0 in the natural number system.
In "math from scratch" implementations like this, natural numbers are typically represented as a linked list where each node holds a binary digit (bit) for a place value, and Zero acts as the base case for all other numbers. Based on the code's context:
Zerois almost certainly a static, readonly instance ofNatural(since it's referenced directly in static methods likeCompareTo).- Its initialization would look something like this (matching the linked-list structure implied by
headandtailproperties):
Here,public static readonly Natural Zero = new Natural(ZeroBit, null);ZeroBitis a constant representing the binary 0 digit (the code checksx.head == ZeroBitto identify a 0 bit in the current position), and thetailisnullbecause zero has no higher-order digit positions.
The comment mentioning "zero means x == y" refers to the return value of CompareTo (0 indicates equality), but the Zero instance itself is the concrete representation of the number 0.
2. Why link the result of ReferenceEquals(x, y) to the x == y check?
The line if (ReferenceEquals(x, y)) return 0; serves two key purposes:
- Performance optimization: If
xandyare references to the exact same object instance, we know immediately they are equal—no need to traverse the linked list of digits recursively to compare each bit. This saves computation time, especially for large natural numbers with many digits. - Guaranteeing equality rules: Equality checks must follow the reflexivity rule (any object is equal to itself). Using
ReferenceEqualshere is the most direct way to enforce this, since identical references always mean identical values in this immutable natural number implementation.
Also, since the == operator for Natural is implemented by calling CompareTo, this check ensures that when you write x == x, it returns true immediately without unnecessary work.
内容的提问来源于stack exchange,提问作者w0051977

