Last active
June 2, 2016 13:22
-
-
Save davidpdrsn/7160634 to your computer and use it in GitHub Desktop.
Bubble sort in SML
This file contains 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
(* 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