Created
September 12, 2011 17:03
-
-
Save mark-d-holmberg/1211775 to your computer and use it in GitHub Desktop.
Clojure Quicksort and More!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Mark Holmberg [email protected] | |
//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