Skip to content

Instantly share code, notes, and snippets.

@jrm2k6
Created January 14, 2014 06:35
Show Gist options
  • Select an option

  • Save jrm2k6/8414074 to your computer and use it in GitHub Desktop.

Select an option

Save jrm2k6/8414074 to your computer and use it in GitHub Desktop.
99haskell problems - 16-20
-- problem 16
myDropEveryNElements :: [a] -> Int -> [a]
myDropEveryNElements l n = if length l > n then
let (first, second) = splitAt n l
in (init first) ++ (myDropEveryNElements second n) else l
myDropEveryNElementsBis :: [a] -> Int -> [a]
myDropEveryNElementsBis l n = helper l n 1 []
where
helper [] n c acc = acc
helper (x:xs) n c acc = if n == c then helper xs n 1 acc else helper xs n (c+1) (acc ++ [x])
-- problem 17
mySplit :: [a] -> Int -> ([a], [a])
mySplit l n = let (first, second) = partition (\(x, y) -> y < n + 1) (zip l [1..])
in (map (\(x, y) -> x) first, map (\(x, y) -> x) second)
-- problem 18
mySlice :: [a] -> Int -> Int -> [a]
mySlice [] _ _ = []
mySlice l inf sup = fst $ splitAt (sup-inf+1) (snd(splitAt (inf-1) l))
mySliceBis :: [a] -> Int -> Int -> [a]
mySliceBis [] _ _ = []
mySliceBis l inf sup = drop (inf-1) $ take sup l
-- problem 19
myRotate :: [a] -> Int -> [a]
myRotate [] _ = []
myRotate l r = let (first, second) = if r >= 0 then splitAt r l else splitAt (length l + r) l
in second ++ first
-- problem 20
myRemoveAt :: Int -> [a] -> (Maybe a, [a])
myRemoveAt _ [] = (Nothing ,[])
myRemoveAt n l = helper n l []
where
helper 0 (x:xs) acc = (Just x, acc ++ xs)
helper n (x:xs) acc = helper (n-1) xs (acc ++ [x])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment