Comparison
comparison operations for any kind of value
Functions
Predicates
The Comparison module provides functions for comparing values of any type. Beyond basic equality checks, it includes ordering operations and advanced comparison features.
Key Concepts
- Works with all value types
- Consistent behavior across different types
- Support for both equality and ordering
- Range checking with
between?
Basic Usage
Simple Comparisons
; equality
print 2 = 2 ; true
print "abc" = "abc" ; true
print 2 = "2" ; false
; inequality
print 2 <> 3 ; true
print "abc" <> "def" ; true
print 2.0 <> 2 ; false
Ordering
; less/greater than
print 2 < 3 ; true
print 3 > 2 ; true
; less/greater or equal
print 2 =< 2 ; true
print 3 >= 2 ; true
Note
The ordering operators work with numbers, strings, dates, and any type that defines ordering.
Range Checking
; check if value is in range (inclusive)
5 <=> 1 10 ; => true
'm' <=> 'a' 'z' ; => true
; or more explicitly
between? 5 1 10 ; => true
Tip
Another way to check if a value is within a given range would becontains?
- or its reversed equivalent -in?
.
Common Patterns
Custom Sorting
The compare
function returns -1, 0, or 1 and is useful for custom sorting:
a: "hello"
b: "world"
result: compare a b ; -1
print ["A comes" (result < 0)? -> "before" -> "after" "B"]
; A comes before B
Identity vs Equality
x: 1`N
y: 1`kg.m/s2 ; actually, that's the definition of 1 Newton!
; equality (same value)
print x = y ; true
; identity (exactly the same?)
print same? x y ; false