Last active
March 17, 2016 16:04
-
-
Save keleshev/b76d86092cc2c31cf744 to your computer and use it in GitHub Desktop.
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
(* Merge two pre-sorted lists into another sorted list *) | |
let rec merge_sorted left right = | |
match left, right with | |
| left_head :: left_tail, right_head :: right_tail -> | |
if left_head < right_head then | |
left_head :: merge_sorted left_tail right | |
else | |
right_head :: merge_sorted left right_tail | |
| [], rest | rest, [] -> rest | |
let () = | |
assert (merge_sorted [1; 1; 1; 2; 30; 40] [15; 30; 35; 50] = [1; 1; 1; 2; 15; 30; 30; 35; 40; 50]) | |
(* Tail-recursive, returning reversed-sorted list *) | |
let rec merge_sorted_reverse ?(accumulator=[]) left right = | |
match left, right with | |
| left_head :: left_tail, right_head :: right_tail -> | |
if left_head < right_head then | |
merge_sorted_reverse ~accumulator:(left_head :: accumulator) left_tail right | |
else | |
merge_sorted_reverse ~accumulator:(right_head :: accumulator) left right_tail | |
| [], rest | rest, [] -> rest @ accumulator | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment