Expand/Shrink

compare

Definition: integer i = compare(object a, b)
Description:
Return -1  if a is less than b,
if objects a and b are identical, or
+1  if a is greater than b.
Atoms are considered to be less than sequences.
Sequences are compared "alphabetically" starting with the first element until a difference is found.

Note that Euphoria typically needs equal() or compare() on each and every non-trivial conditional test, whereas Phix can just use the more natural infix operators =, <=, etc. Apart from the obvious legacy code and compatibility with Euphoria, compare is also very useful in sort routines and the like.

You can also use sq_cmp() to obtain nested element-wise results.
pwa/p2js: Supported.
Example 1:
x = compare({1,2,{3,{4}},5}, {2-1,1+1,{3,{4}},6-1})
-- identical, x is 0
Example 2:
if compare("ABC", "ABCD") < 0 then   -- -1
    -- will be true: ABC is "less" because it is shorter
end if
Example 3:
x = compare({12345, 99999, -1, 700, 2},
            {12345, 99999, -1, 699, 3, 0})
-- x will be 1 because 700 > 699
Example 4:
x = compare(’a’, "a")
-- x will be -1 because ’a’ is an atom
--                while "a" is a sequence
Implementation: Implemented as %opScmp in builtins\VM\pJcc.e (an autoinclude) - be warned however it is low-level complicated stuff that you do not need to know, as hinted by example 3 above things can get very messy digging ever deeper into nested sequences looking for the first discrepancy. sq_cmp() is implemented in builtins\psqop.e
See Also: equal, min, max, relational operators, sequence operations
Expand/Shrink