Difference between revisions of "99 questions/Solutions/18"

From HaskellWiki
Jump to: navigation, search
 
(another solution using splitAt)
Line 8: Line 8:
   
 
Or, an iterative solution:
 
Or, an iterative solution:
  +
 
<haskell>
 
<haskell>
 
slice :: [a]->Int->Int->[a]
 
slice :: [a]->Int->Int->[a]
Line 26: Line 27:
 
| k < 1 = []
 
| k < 1 = []
 
| otherwise = x:slice xs (i - 1) (k - 1)
 
| otherwise = x:slice xs (i - 1) (k - 1)
  +
</haskell>
  +
  +
Another way using <hask>splitAt</hask>, though not nearly as elegant as the <hask>take</hask> and <hask>drop</hask> version:
  +
  +
<haskell>
  +
slice :: [a] -> Int -> Int -> [a]
  +
slice xs i k = chunk
  +
where chop = snd $ splitAt i' xs -- Get the piece starting at i
  +
chunk = fst $ splitAt (k - i') chop -- Remove the part after k
  +
i' = i - 1
 
</haskell>
 
</haskell>

Revision as of 01:38, 16 July 2010

(**) 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)

Another way using splitAt, though not nearly as elegant as the take and drop version:

slice :: [a] -> Int -> Int -> [a]
slice xs i k = chunk
  where chop  = snd $ splitAt i' xs          -- Get the piece starting at i
        chunk = fst $ splitAt (k - i') chop  -- Remove the part after k
        i'    = i - 1