(* A Polymorphic QuickSort function for any list. Stephen Freund cs334 *) (* Always include these at the top of your SML files so large datatype values and lists will print fully *) Control.Print.printDepth := 100; Control.Print.printLength := 100; (* partition: (('a * 'a -> bool) * 'a * 'a list) -> ('a list * 'a list) In this version, you must supply a lessThan fuction for comparing values. *) fun partition (lessThan, pivot, nil) = (nil, nil) | partition (lessThan, pivot, x::xs) = let val (smaller, bigger) = partition(lessThan, pivot, xs) in if lessThan(x,pivot) then (x::smaller, bigger) else (smaller, x::bigger) end; (* qsort: ('a * 'a -> bool) * 'a list -> 'a list *) fun qsort (lessThan, nil) = nil | qsort (lessThan, p::rest) = let val (smaller, bigger) = partition(lessThan, p,rest) in qsort (lessThan, smaller) @ [p] @ qsort(lessThan, bigger) end; qsort (op<, [6,23,6,3,78,23,12,6,7,34,7]); qsort ((fn (x,y) => (abs x) < (abs y)), [~3, 5, 2, ~1]); qsort (op<, ["moo", "purple", "cow", "wombat"]);