99 questions/Solutions/18
< 99 questions | Solutions
Jump to navigation
Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
(**) Extract a slice from a list.
Given two indices, i and k, the slice is the list containing the elements between the i'th and k'th element of the original list (both limits included). Start counting the elements with 1.
slice xs (i+1) k = take (k-i) $ drop i xs
Or, an iterative solution:
slice :: [a]->Int->Int->[a]
slice lst 1 m = slice' lst m []
where
slice' :: [a]->Int->[a]->[a]
slice' _ 0 acc = reverse acc
slice' (x:xs) n acc = slice' xs (n - 1) (x:acc)
slice (x:xs) n m = slice xs (n - 1) (m - 1)
Or:
slice :: [a] -> Int -> Int -> [a]
slice (x:xs) i k
| i > 1 = slice xs (i - 1) (k - 1)
| k < 1 = []
| otherwise = x:slice xs (i - 1) (k - 1)