Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify if a list is sorted?

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.

like image 261
marius Avatar asked Feb 03 '14 22:02

marius


2 Answers

The simplest solution:

(apply <= mylist)

>= also works for reverse sorting

like image 55
noisesmith Avatar answered Oct 13 '22 07:10

noisesmith


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  
like image 40
Arthur Ulfeldt Avatar answered Oct 13 '22 07:10

Arthur Ulfeldt