Skip to content

Instantly share code, notes, and snippets.

@finnp
Created August 22, 2013 20:48
Show Gist options
  • Save finnp/6312607 to your computer and use it in GitHub Desktop.
Save finnp/6312607 to your computer and use it in GitHub Desktop.
99 Problems in Haskell
-- Problem 1
myLast :: [a] -> a
myLast xs = xs !! (length xs - 1)
-- Problem 2
myButLast :: [a] -> a
myButLast xs = (drop (length xs - 2) xs) !! 0
-- Problem 3
elementAt :: [a] -> Int -> a
elementAt xs i = xs !! (i-1)
-- Problem 4
myLength :: [a] -> Int
myLength = foldl (\a b -> a + 1) 0
-- Problem 5
myReverse :: [a] -> [a]
myReverse = foldl (\a b -> b:a) []
-- Problem 6
isPalindrome :: (Eq a ) => [a] -> Bool
isPalindrome xs = null (foldl (\a b -> if (head a) == b then tail a else a) (reverse xs) xs)
-- Problem 7
data NestedList a = Elem a | List [NestedList a]
flatten :: NestedList a -> [a]
flatten (Elem x) = [x]
flatten (List xs) = foldl (\a b -> a ++ (flatten b)) [] xs
-- Problem 8
compress :: (Eq a) => [a] -> [a]
compress (x:xs) = foldl (\a b -> if last a == b then a else a ++ [b] ) [x] xs
-- Problem 9
--pack (x:xs) = foldl (\a b -> if (last.last) a == b then (init a) ++ [b : last a] else a ++ [[b]]) [[x]] xs
pack :: (Eq a) => [a] -> [[a]]
pack xs = foldr (\b a -> if (head.head) a == b then (b : head a): tail a else [b]:a) [[last xs]] (init xs)
-- Problem 10
encode :: (Eq a) => [a] -> [(Int, a)]
encode xs = foldr (\b a -> (length b, head b):a) [] (pack xs)
-- Problem 31
isPrime :: Integer -> Bool
isPrime n = if n < 2 then False else foldl (\acc b -> acc && ((mod n b) /= 0) ) True [2..n-1]
-- 128 Zeichen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment