Skip to content

Instantly share code, notes, and snippets.

@dmcardle
Last active August 29, 2015 14:22
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 dmcardle/0b5fbd3516df4c0211af to your computer and use it in GitHub Desktop.
Save dmcardle/0b5fbd3516df4c0211af to your computer and use it in GitHub Desktop.
Haskell 99 Problems
{- Haskell 99 Problems
- https://wiki.haskell.org/99_questions/1_to_10
-}
reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) = (reverse' xs) ++ [x]
myLast :: [a] -> a
myLast [] = error "no last element"
myLast [x] = x
myLast (x:xs) = myLast xs
myButLast :: [a] -> a
myButLast [] = error "no second-to-last element"
myButLast [x,y] = x
myButLast (x:xs) = myButLast xs
myButLast' = last . init
elementAt :: [a] -> Int -> a
elementAt [] _ = error "No element in empty list"
elementAt (x:xs) 0 = x
elementAt (x:xs) n = elementAt xs (n-1)
myLength :: [a] -> Int
myLength [] = 0
myLength (x:xs) = 1 + myLength xs
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome [] = True
isPalindrome [x] = True
isPalindrome xs = (a == b) && isPalindrome (tail (init xs))
where
a = head xs
b = last xs
compress :: (Eq a) => [a] -> [a]
compress [] = []
compress [x] = [x]
compress (x:y:zs)
| x == y = compress (y:zs)
| otherwise = x : compress (y:zs)
pack :: (Eq a) => [a] -> [[a]]
pack [] = []
pack (x:xs) = group : pack remaining
where
group = takeWhile (==x) (x:xs)
remaining = dropWhile (==x) (x:xs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment