txm03
txm03

Reputation: 51

Create a function with take the first n and last n elements

I want to create a function that keep the first n as well as the last n elements are, all other elements are dropped.

If there are less than or equal to 2n elements, all elements are kept.

dropTake 4 [ 0 , 1 , 2 , 3 , 4 , 5 , 6 ] => [ 0 , 1 , 2 , 3 , 4 , 5 , 6 ]

My idea was that:

dropTake :: Int -> [a] -> [a]
dropTake n [] = []
dropTake n (x:xs) 
    | n > 0 = take n (x:xs) ++ drop (length xs - n) xs
    | n < 0 = error "Vorraussetzung nicht erfüllt"

Now the command If there are less than or equal to 2n elements, all elements are kept is missing, but how can I wirte it down?

Upvotes: 0

Views: 288

Answers (1)

chepner
chepner

Reputation: 530970

One way would be to simply compare 2*n with the length of the list, and return the list as-is if appropriate.

dropTake :: Int -> [a] -> [a]
dropTake n xs | length xs <= 2*n = xs
dropTake n [] = []
dropTake n (x:xs) 
    | n > 0 = take n (x:xs) ++ drop (length xs - n) xs
    | n < 0 = error "Vorraussetzung nicht erfüllt"

Upvotes: 1

Related Questions