Created
October 20, 2011 01:51
-
-
Save benjamintanweihao/1300218 to your computer and use it in GitHub Desktop.
Haskell Example for CS2104
This file contains 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
### Eliminate consecutive duplicates of list elements. ### | |
compress [] = [] | |
compress (x:xs) = [x] ++ (compress $ dropWhile (== x) xs | |
### Flatten a nested list structure. ### | |
flatten :: NestedList a -> [a] | |
flatten (Elem a ) = [a] | |
flatten (List (x:xs)) = flatten x ++ flatten (List xs) | |
flatten (List []) = [] | |
### Pack consecutive duplicates of list elements into sublists. If a list contains repeated | |
elements they should be placed in separate sublists. | |
### | |
Example: | |
(pack '(a a a a b c c a a d e e e e)) | |
((A A A A) (B) (C C) (A A) (D) (E E E E)) | |
pack :: (Eq a) => [a] -> [[a]] | |
pack = foldr func [] | |
where func x [] = [[x]] | |
func x (y:xs) = | |
if x == (head y) then ((x:y):xs) else ([x]:y:xs) | |
### Duplicate the elements of a list. ### | |
dupli [] = [] | |
dupli (x:xs) = x:x:dupli xs | |
### Drop every N'th element from a list. ### | |
dropEvery :: [a] -> Int -> [a] | |
dropEvery [] _ = [] | |
dropEvery list count = (take (count-1) list) ++ dropEvery (drop count list) count | |
### Split a list into two parts; the length of the first part is given. ### | |
Example: | |
split "abcdefghik" 3 | |
("abc", "defghik") | |
Solution using take and drop: | |
split xs n = (take n xs, drop n xs) | |
### Prime Numbers using the Sieve ### | |
primesR a b = takeWhile (<= b) $ dropWhile (< a) $ sieve [2..] | |
where sieve (n:ns) = n:sieve [ m | m <- ns, m `mod` n /= 0 ] | |
### concatMap ### | |
concatMap :: (a -> [b]) -> [a] -> [b] | |
concatMap f = foldr ((++) . f) [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment