Reputation: 1613
How can I, in Clojure, verify is a list of numbers is sorted?
(def my-list (list 1 2 3 1 4 2 2 4))
sorted?
only returns true if the collection implements the sorted
interface. I was looking for a reduce
operation that would iterate the list pairwise, such as (reduce < my-list)
.
I understand I could manually create pairs and compare these:
(letfn [(pair [l] (if (= (count l) 2) (list l) (cons (take 2 l) (pair (rest l)))))]
(every? #(apply < %) (pair my-list)))
But that seems unnecessarily complex. It really seems to me as if I'm missing a basic function.
Upvotes: 9
Views: 1672
Reputation: 20194
The simplest solution:
(apply <= mylist)
>=
also works for reverse sorting
Upvotes: 26
Reputation: 91597
I would do a single pass over overlapping pairs of numbers and check they are <=
(as you mention) because it is O(n), though you don't need to manually make pairs.
user> (partition-all 2 1 [1 2 3 4 5 6])
((1 2) (2 3) (3 4) (4 5) (5 6) (6))
user> (every? #(apply <= %) (partition-all 2 1 [1 2 3 4 6 5]))
false
user> (every? #(apply <= %) (partition-all 2 1 [1 2 3 4 5 6]))
true
Upvotes: 5
Reputation: 2075
You could sort the list and compare it to the original:
(= my-list (sort my-list))
Example:
> (def my-list (list 1 2 3 1 4 2 2 4))
#'sandbox3825/my-list
> (= my-list (sort my-list))
false
> (def my-list (list 1 2 3 4))
#'sandbox3825/my-list
> (= my-list (sort my-list))
true
Upvotes: 1