Home > Net >  How can I cut from a list in haskell?
How can I cut from a list in haskell?

Time:10-24

Implement the list function, which cuts a part of a list! The first parameter is the index from which the sublist begins and the second parameter is the length of the cut.

list :: Int -> Int -> [b] -> [b]
list a b (x: xs) = x: sublist (a: a   b) xs

I tried this recursive solution, but it is not working. I do not have any idea how can I make this code. Can I get some help?

CodePudding user response:

Leverage the prelude. First drop, then take:

cut :: Int -> Int -> [a] -> [a]
cut m n = take n . drop m

For instance:

> cut 2 3 [0, 1, 1, 2, 3, 5, 8, 13]
[1,2,3]

Alternatively, if you are set on rolling your own recursive implementation:

cut' :: Int -> Int -> [a] -> [a]
cut' 0 0 xs       = []                    -- done
cut' _ _ []       = []                    -- done
cut' 0 n (x : xs) = x : cut' 0 (n - 1) xs -- take
cut' m n (x : xs) = cut' (m - 1) n xs     -- drop

Indeed:

> cut' 2 3 [0, 1, 1, 2, 3, 5, 8, 13]
[1,2,3]
  • Related