Last active
December 27, 2015 17:09
-
-
Save jrm2k6/7359664 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| -- problem 1 | |
| myLast :: [a] -> a | |
| myLast (x:[]) = x | |
| myLast (x:xs) = myLast xs | |
| myLast [] = error "Empty list" | |
| myOneLineLast :: [a] -> a | |
| myOneLineLast x = x !! (length x - 1) | |
| -- problem 2 | |
| myButLast :: [a] -> a | |
| myButLast (x:[]) = error "One element list" | |
| myButLast (x:xs) = if length xs == 1 then x else myButLast xs | |
| myButLast [] = error "Empty list" | |
| myOneLineButLast :: [a] -> a | |
| myOneLineButLast x = x !! (length x - 2) | |
| -- problem 3 | |
| elementAt :: [a] -> Int -> a | |
| elementAt (x:xs) 1 = x | |
| elementAt (x:xs) v = elementAt xs (v-1) | |
| elementAt _ _ = error "Index out of bounds" | |
| myOneLineElementAt :: [a] -> Int -> a | |
| myOneLineElementAt l v = l !! (v-1) | |
| -- problem 4 | |
| myLength :: [a] -> Int | |
| myLength l = foldl (\x o-> x+1) 0 l | |
| myLength' :: [a] -> Int | |
| myLength' = sum . map (\_ -> 1) | |
| -- problem 5 | |
| myReverse :: [a] -> [a] | |
| myReverse l = foldl (\acc x -> x:acc) [] l | |
| myReverse' :: [a] -> [a] | |
| myReverse' l = foldr (\x acc -> acc ++ [x]) l [] |
This file contains hidden or 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
| -- problem 6 | |
| isPalindrome :: Eq a => [a] -> Bool | |
| isPalindrome l = (reverse l) == l | |
| isPalindrome' :: Eq a => [a] -> Bool | |
| isPalindrome' [] = True | |
| isPalindrome' (x:[]) = True | |
| isPalindrome' l = (head l == last l) && isPalindrome (init $ tail l) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment