(* balanced-inefficient.ml *) (* a straightforward implementation -- very inefficient on long lists *) (* val insert : 'a -> 'a list -> 'a list if ys is sorted in strictly ascending order and x appears in ys, then insert x ys = ys if ys is sorted in strictly ascending order and x does not appear in ys, then insert x ys is the result of putting x :: ys in strictly ascending order *) let rec insert x ys = match ys with [] -> [x] | y :: ys as zs -> match compare x y with -1 -> x :: zs | 0 -> zs | _ -> y :: insert x ys (* val sort : 'a list -> 'a list sort xs has the same elements as xs, but they are listed in strictly ascending order *) let rec sort xs = match xs with [] -> [] | x :: xs -> insert x (sort xs) (* val prefixes : 'a list -> 'a list list prefixes xs returns all of the PREFIXES of xs, i.e., all of lists us such that us @ vs = xs for some vs; they are listed in strictly ascending order *) let rec prefixes xs = match xs with [] -> [[]] | x :: xs -> [] :: List.map (function ys -> x :: ys) (prefixes xs) (* val sublists : 'a list -> 'a list list sublists xs returns all of the sublists of xs, listed in strictly ascending order *) let rec sublists xs = match xs with [] -> [[]] | _ :: xs as zs -> sort(prefixes zs @ sublists xs) (* val sum : int list -> int sum xs returns the sum of xs *) let rec sum xs = match xs with [] -> 0 | x :: xs -> x + sum xs (* val null : 'a list -> bool null xs tests whether xs is empty *) let null xs = match xs with [] -> true | _ -> false (* val isBalanced : int list -> bool isBalanced xs tests whether xs is balanced *) let isBalanced xs = let len = List.length xs in len <> 0 && sum xs = 0 && List.for_all (function ys -> null ys || List.length ys = len || sum ys <> 0) (sublists xs) (* val balanced : 'a list -> 'a list list balanced xs returns the balanced sublists of xs, listed in strictly ascending order *) let balanced xs = List.filter isBalanced (sublists xs)