Home > Net >  Create a functin with take the first n and last n elements
Create a functin with take the first n and last n elements

Time:12-12

I want to create a fucntion 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?

CodePudding user response:

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"
  • Related