Skip to content

Instantly share code, notes, and snippets.

@mark-d-holmberg
Created September 12, 2011 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mark-d-holmberg/1211775 to your computer and use it in GitHub Desktop.
Save mark-d-holmberg/1211775 to your computer and use it in GitHub Desktop.
Clojure Quicksort and More!
//Mark Holmberg tiggers.no.tail@gmail.com
//CS350, Programming Languages
//date: Mon Sep 12 09:33:11 MDT 2011
//Clojure
//http://en.wikipedia.org/wiki/Quicksort
((fn [x] (* x x)) 5)
//calling a function with only one parameter
#(* % %)
//square all the elements in a list
//as a vector
(map #(* % %) [1 2 3 4 5])
//as a list
(map #(* % %) '(1 2 3 4 5))
//how to define our own map function called 'MyMap'
(defn mymap [f lst] (if (empty? lst) nil (cons (f (first lst)) (mymap f(rest lst)))))
//the test
(mymap #(* % %) '(1 2 3 4 5))
//filter
(filter nil? '(1 2 nil 3 4))
//grab everything that isn't nil
(filter #(not (nil? %)) '(1 2 nil 3 4))
(defn myfilter [f lst]
(if (empty? lst)
lst
(if (f (first lst))
(cons (first lst) (myfilter f(rest lst)))
(myfilter f(rest lst)))))
//the test
(myfilter #(not (nil? %)) '(1 2 nil 3 4))
//A quicksort function
(defn mypartition [pivot lst]
(list (filter #(<= % pivot) lst)
(filter #(> % pivot) lst)))
(defn append [a b]
(if (empty? a)
b
(cons (first a) (append (rest a) b))))
//a good start but not finished
(defn quicksort [lst]
(if (< (count lst) 2)
lst
(let [pivot (first lst)
[less greater] (mypartition pivot (rest lst))]
(append (quicksort less)
(cons pivot (quicksort greater))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment