Documentation – Why Use ‘Equivalent to’ Instead of ‘Is’?

ccompilerdocumentationpython

Why does the documentation on some languages say "equivalent to" rather than "is"?

For example, the Python Docs say

itertools.chain(*iterables)

Equivalent to:

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

Or this C++ reference on find_if:

The behavior of this function template is equivalent to:

template<class InputIterator, class UnaryPredicate>
  InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) return first;
    ++first;
  }
  return last;
}

If that's not the actual code, can't they post it? And if it is the actual code, why do they have to say it's "Equivalent" rather than simply "is"?

Best Answer

Because the standard writers don't want to actually assert an implementation. They want to define what it does, but not necessarily how it does it. So, for example, if you look at the GNU C++ version of find_if, you will see that the implementation is slightly different from what you give, which is based on the C++ standard:

template<typename _InputIterator, typename _Predicate>
inline _InputIterator
__find_if(_InputIterator __first, _InputIterator __last,
    _Predicate __pred, input_iterator_tag)
{
    while (__first != __last && !bool(__pred(*__first)))
     ++__first;
       return __first;
}

This is functionally equivalent to what the standard has, but not exactly the same. This gives compiler writers flexibility. There may be a better way to do it for a particular platform. The implementor may wish to use a different coding style.

This is particularly true for scripting languages like python in that the implementor may decided to implement in a completely different language for performance reasons. Someone implementing python may, for instance, write itertools.chain(*iterables) in C++. This is perfectly fine if the standard says "equivalent to" as long as the code does the same as the provided python. If the standard said "is" instead, then implementors would be required to either implement in that language, or not meet the standard.

In summary:

  1. Because they don't want to prevent an implementation from writing better code than the standard provided
  2. Because they don't want to prevent an implementation from using an entirely different language, to improve performance
Related Topic