# compare

Definition: | integer i = compare(object a, b)
Description: |
Return -1 | if a is less than b,
0 | 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
Technicalia | Be advised that sq_cmp() yields a character-wise comparison on (nested) strings, and throws an exception if their lengths are not the same. It would however be fine in Example 4, yielding {0}, because in that case it compares the atom 'a' against each character of "a" in turn, and of course {0} bears no relation to the -1 result shown above from calling compare() directly, despite the fact that it actually invokes compare().