/ Published in: Haskell
I had originally started these problems from #10 (Run-length encoding). I went back and did 1-8 for completeness.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
import Data.List list1 = [1,2,3,4,5,6] -- Problem 1: find the last element of a list lastList :: [a] -> a lastList (x:[]) = x lastList (x:xs) = lastList xs -- Problem 2: Find the last but one element of a list. lastButOne :: [a] -> a lastButOne [x,_] = x lastButOne (_:xs) = lastButOne xs -- Problem 3: Find the K'th element of a list. The first element in the list is number 1. elementAt s@(x:xs) n -- Problem 4: find the number of elements of a list countList [] = 0 countList (x:xs) = 1 + countList xs -- Problem 5: reverse a list (I assume, not using "reverse") -- Problem 6: find out whether a list is a palindrome isPalindrome [] = True in (xs2 == xs) -- Problem 7: flatten a nested list structure -- NOTE: This doesn't strictly solve the problem. May want to revisit later. flatten :: [[a]] -> [a] {- Problem 8: Eliminate consecutive duplicates of list elements. If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed. > compress ["a","a","a","a","b","c","c","a","a","d","e","e","e","e"] ["a","b","c","a","d","e"] -} -- excellent opportunity to play around with mapAccumL -- the simplest solution from the Wiki {- Problem 9: Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements they should be placed in separate sublists. *Main> pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e'] ["aaaa","b","cc","aa","d","eeee"] -} pack = group
URL: http://www.haskell.org/haskellwiki/99_questions/1_to_10