-
-
Save WhiteBlackGoose/ce6290b63a6521551bbc9fa9d469be76 to your computer and use it in GitHub Desktop.
Merge sort implemented in the nix programming language
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
nix-repl> sort = import ./mergesort.nix | |
nix-repl> sort [ 3 1 2 8 0 2 3 5 ] | |
[ 0 1 2 2 3 3 5 8 ] |
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
let re = func: func func; in | |
re ( | |
sort: input: | |
with builtins; | |
let | |
zip = re (zip: l1: l2: | |
if length l1 == 0 then | |
l2 | |
else if length l2 == 0 then | |
l1 | |
else | |
if head l1 < head l2 then | |
[ (head l1) ] ++ zip zip (tail l1) l2 | |
else | |
[ (head l2) ] ++ zip zip l1 (tail l2) | |
); | |
skip = re (skip: l: n: | |
if n == 0 then | |
l | |
else | |
skip skip (tail l) (n - 1) | |
); | |
take = re (take: l: n: | |
if n == 0 then | |
[] | |
else | |
[ (head l) ] ++ take take (tail l) (n - 1) | |
); | |
in | |
if length input <= 1 then | |
input | |
else | |
zip | |
(sort sort (take input (length input / 2))) | |
(sort sort (skip input (length input / 2))) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment