Skip to content

Instantly share code, notes, and snippets.

@WhiteBlackGoose
Last active June 15, 2023 09:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WhiteBlackGoose/ce6290b63a6521551bbc9fa9d469be76 to your computer and use it in GitHub Desktop.
Save WhiteBlackGoose/ce6290b63a6521551bbc9fa9d469be76 to your computer and use it in GitHub Desktop.
Merge sort implemented in the nix programming language
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 ]
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