Skip to content

Instantly share code, notes, and snippets.

@xerxesb
Created May 25, 2012 13:38
Show Gist options
  • Save xerxesb/2788221 to your computer and use it in GitHub Desktop.
Save xerxesb/2788221 to your computer and use it in GitHub Desktop.
Xerxes solutions to typeclass problems
data List a = Elem a | List [List a] deriving (Show)
flatten' :: List a -> [a]
flatten' (Elem x) = [x]
flatten' (List (x:xs)) = flatten' x ++ flatten' (List xs)
flatten' (List []) = []
data Tree a = Empty | Node a (Tree a) (Tree a)
deriving (Eq, Show, Read)
treeInsert :: Ord a => Tree a -> a -> Tree a
treeInsert Empty a = Node a Empty Empty
treeInsert tree@(Node v l r) a
| v > a = Node v (treeInsert l a) r
| v < a = Node v l (treeInsert r a)
| v == a = tree
treeFromList :: Ord a => [a] -> Tree a
--treeFromList [] = Empty
--treeFromList (x:xs) = treeInsert (treeFromList xs) x
--treeFromList xs = foldr (\x acc -> treeInsert acc x) Empty xs
--treeFromList = foldr (\x acc -> flip treeInsert x acc) Empty
treeFromList = foldr (flip treeInsert) Empty
class Mappable m where
mmap :: (a -> b) -> m a -> m b
instance Mappable List where
mmap f (Elem x) = Elem (f x)
mmap f (List xs) = List(map (mmap f) xs)
mmap' :: (a->b) -> List a -> List b
mmap' f (Elem x) = Elem (f x)
--mmap' f (List []) = List []
--mmap' f (List (x:xs)) = List (mappedFirst : mappedRest)
-- where
-- mappedFirst = mmap' f x
-- mappedRest = map (\y -> mmap' f y) xs
--mmap' f (List xs) = List(map (\y -> mmap' f y) xs)
mmap' f (List xs) = List(map (mmap' f) xs)
instance Mappable Tree where
mmap f Empty = Empty
mmap f (Node v l r) = Node (f v) (mmap f l) (mmap f r)
increaseAll :: (Enum a, Mappable m) => m a -> m a
increaseAll xs = mmap succ xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment