Skip to content

Instantly share code, notes, and snippets.

@davidpdrsn
Last active June 2, 2016 13:22
Show Gist options
  • Save davidpdrsn/7160634 to your computer and use it in GitHub Desktop.
Save davidpdrsn/7160634 to your computer and use it in GitHub Desktop.
Bubble sort in SML
(* sorted : int list -> bool
* check if a list of ints is sorted *)
fun sorted [] = true
| sorted [x] = true
| sorted (x::y::xs) = x < y andalso sorted (y::xs)
val sorted_test1 = sorted [1,2,3]
val sorted_test2 = not (sorted [2,1,3])
val sorted_test3 = not (sorted [2,3,1])
val sorted_test4 = sorted []
local
(* bSort' : int list -> int list
* sort a list of ints just a little *)
fun bSort' [] = []
| bSort' [x] = [x]
| bSort' (x::y::xs) = case Int.compare (x,y) of
GREATER => y :: x :: xs
| EQUAL => x :: y :: xs
| LESS => x :: bSort' (y::xs)
(* function for doing fix point iteration *)
fun fix f x = if f x = x then x
else fix f (f x)
in
(* bSort : int list -> int list
using bSort' and fix point interation, sort a list of ints *)
fun bSort x = fix bSort' x
end
val bSort_test1 = bSort [5,3,4,2,1] = [1,2,3,4,5]
val bSort_test2 = bSort [] = []
val bSort_test3 = bSort [1,2,3] = [1,2,3]
val bSort_test4 = bSort [4,3,2,1] = [1,2,3,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment