Problem 18

99 Haskell Problems

Problem 18

(**) 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 '(a b c d e f g h i k) 3 7)
(C D E F G)

Example in Haskell:

*Main> slice ['a','b','c','d','e','f','g','h','i','k'] 3 7


slice :: [a] -> Int -> Int -> [a]
slice [] _ _ = []
slice (x:xs) a b
    | a > 1 && b > 0 = slice xs (a-1) (b-1)
    | b > 0 = x:(slice xs 0 (b-1))
    | otherwise = []

This was very similar to the previous problem. I used the input as an indices for counting what to extract out.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s