mirror of
https://github.com/anoma/juvix.git
synced 2024-12-12 14:28:08 +03:00
59 lines
1.4 KiB
Plaintext
59 lines
1.4 KiB
Plaintext
-- merge sort
|
|
module test032;
|
|
|
|
import Stdlib.Prelude open;
|
|
|
|
split : {A : Type} → Nat → List A → Pair (List A) (List A)
|
|
| zero xs := nil, xs
|
|
| (suc n) nil := nil, nil
|
|
| (suc n) (x :: xs) :=
|
|
case split n xs of {l1, l2 := x :: l1, l2};
|
|
|
|
terminating
|
|
merge' : List Nat → List Nat → List Nat
|
|
| nil ys := ys
|
|
| xs nil := xs
|
|
| xs@(x :: xs') ys@(y :: ys') :=
|
|
ite (x <= y) (x :: merge' xs' ys) (y :: merge' xs ys');
|
|
|
|
terminating
|
|
sort : List Nat → List Nat
|
|
| xs :=
|
|
let
|
|
n : Nat := length xs;
|
|
in ite
|
|
(n <= 1)
|
|
xs
|
|
case split (div n 2) xs of {l1, l2 :=
|
|
merge' (sort l1) (sort l2)};
|
|
|
|
terminating
|
|
uniq : List Nat → List Nat
|
|
| nil := nil
|
|
| (x :: nil) := x :: nil
|
|
| (x :: xs@(x' :: _)) :=
|
|
ite (x == x') (uniq xs) (x :: uniq xs);
|
|
|
|
gen : List Nat → Nat → (Nat → Nat) → List Nat
|
|
| acc zero f := acc
|
|
| acc (suc n) f := gen (f (suc n) :: acc) n f;
|
|
|
|
gen2 : List (List Nat) → Nat → Nat → List (List Nat)
|
|
| acc m zero := acc
|
|
| acc m (suc n) :=
|
|
gen2 (gen nil m ((+) (suc n)) :: acc) m n;
|
|
|
|
printListNatLn : List Nat → IO
|
|
| nil := printStringLn "nil"
|
|
| (x :: xs) :=
|
|
printNat x >>> printString " :: " >>> printListNatLn xs;
|
|
|
|
sum : List Nat → Nat
|
|
| nil := 0
|
|
| (h :: t) := h + sum t;
|
|
|
|
main : Nat :=
|
|
sum (take 10 (uniq (sort (flatten (gen2 nil 6 40)))))
|
|
+ sum (take 10 (uniq (sort (flatten (gen2 nil 9 80)))))
|
|
+ sum (take 10 (uniq (sort (flatten (gen2 nil 6 80)))));
|