Skip to content

Instantly share code, notes, and snippets.

@jrm2k6
Created January 10, 2014 18:48
Show Gist options
  • Select an option

  • Save jrm2k6/8360224 to your computer and use it in GitHub Desktop.

Select an option

Save jrm2k6/8360224 to your computer and use it in GitHub Desktop.
Haskell 99 problems - 10 to 15
import Data.List
-- problem 11
data Element a = Multiple a Int | Single a deriving (Show, Eq)
encodeModified :: Eq a => [a] -> [Element a]
encodeModified [] = []
encodeModified l = map (\x -> if (length x > 1) then Multiple (head x) (length x) else Single (head x)) $ group l
-- problem 12
decodeModified :: Eq a => [Element a] -> [a]
decodeModified [] = []
decodeModified l = concatMap innerDecode l
where
innerDecode (Single v) = [v]
innerDecode (Multiple v t) = replicate t v
-- problem 13
encodeBis :: Eq a => [a] -> [(Int, a)]
encodeBis l = foldl helper [] l
where
helper [] e = [(1, e)]
helper acc e
| e == (snd $ last acc) = init acc ++ [((fst $ last acc) + 1 , snd $ last acc)]
| otherwise = acc ++ [(1, e)]
encodeDirect :: Eq a => [a] -> [Element a]
encodeDirect [] = []
encodeDirect l = concatMap innerEncode (encodeBis l)
where
innerEncode (1, v) = [Single v]
innerEncode (t, v) = [Multiple v t]
-- problem 14
myDuplicate :: [a] -> [a]
myDuplicate = foldl (\acc x -> acc ++ (replicate 2 x)) []
myDuplicateEvenSimpler :: [a] -> [a]
myDuplicateEvenSimpler = foldl (\acc x -> acc ++ [x,x]) []
--problem 15
myRepli :: [a] -> Int -> [a]
myRepli l v = foldl (\acc x -> acc ++ (replicate v x)) [] l
myDuplicateUsingRepli l = myRepli l 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment