Created
January 19, 2016 04:03
-
-
Save jtobin/8fe373e19aa1a232f0d3 to your computer and use it in GitHub Desktop.
Sorting (Slowly) With Style
This file contains 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
{-# LANGUAGE DeriveFunctor #-} | |
{-# LANGUAGE TypeFamilies #-} | |
import Data.Functor.Foldable | |
data ListF a r = | |
ConsF a r | |
| NilF | |
deriving (Show, Functor) | |
type List a = Fix (ListF a) | |
fromList :: [a] -> List a | |
fromList = ana coalg . project where | |
coalg Nil = NilF | |
coalg (Cons h t) = ConsF h (project t) | |
mapHead :: (a -> a) -> List a -> List a | |
mapHead f = apo coalg . project where | |
coalg NilF = NilF | |
coalg (ConsF h t) = ConsF (f h) (Left t) | |
cat :: List a -> List a -> List a | |
cat l0 l1 = apo coalg (project l0) where | |
coalg NilF = case project l1 of | |
NilF -> NilF | |
ConsF h t -> ConsF h (Left t) | |
coalg (ConsF x l) = case project l of | |
NilF -> ConsF x (Left l1) | |
ConsF h t -> ConsF x (Right (ConsF h t)) | |
knockback :: Ord a => List a -> List a | |
knockback = apo coalg . project where | |
coalg NilF = NilF | |
coalg (ConsF x l) = case project l of | |
NilF -> ConsF x (Left l) | |
ConsF h t | |
| x <= h -> ConsF x (Left l) | |
| otherwise -> ConsF h (Right (ConsF x t)) | |
insertionSort :: Ord a => List a -> List a | |
insertionSort = cata (knockback . embed) | |
knockbackL :: Ord a => [a] -> [a] | |
knockbackL = apo coalg . project where | |
coalg Nil = Nil | |
coalg (Cons x l) = case project l of | |
Nil -> Cons x (Left l) | |
Cons h t | |
| x <= h -> Cons x (Left l) | |
| otherwise -> Cons h (Right (Cons x t)) | |
insertionSortL :: Ord a => [a] -> [a] | |
insertionSortL = cata (knockbackL . embed) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment