Skip to content

Instantly share code, notes, and snippets.

@Ceasar
Created January 3, 2013 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ceasar/4439613 to your computer and use it in GitHub Desktop.
Save Ceasar/4439613 to your computer and use it in GitHub Desktop.
Proof of concept abstraction of divide and conquer. Doesn't really work very well...
-- In Divide and Conquer, we solve a problem recursively, applying three steps at each level of recursion.
dnc :: (a -> [a]) -> (a -> b) -> ([b] -> b) -> a -> b
dnc divide con comb x = case divide x of
[] -> con x
xs -> comb $ map (dnc divide con comb) xs
split :: [a] -> ([a], [a])
split [] = ([], [])
split [x] = ([x], [])
split (x:y:zs) = (x:xs, y:ys) where (xs, ys) = split zs
merge :: Ord a => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys)
| x < y = x : merge xs (y:ys)
| otherwise = y : merge (x:xs) ys
mergesort :: Ord a => [a] -> [a]
mergesort = dnc split' id merge'
where
split' xs = case split xs of
([], []) -> []
([], r) -> []
(l, []) -> []
(l, r) -> [l, r]
merge' :: Ord a => [[a]] -> [a]
merge' [] = []
merge' [x] = x
merge' (x:y:zs) = merge' (merge x y:zs)
main = undefined
@Ceasar
Copy link
Author

Ceasar commented Jan 3, 2013

This is just map reduce.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment