Remove elements by index in haskell

后端 未结 8 881

I\'m new in haskell and I\'m looking for some standard functions to work with lists by indexes.

My exact problem is that i want to remove 3 elements after every 5. If i

8条回答
  •  心在旅途
    2021-02-07 23:47

    the take and drop functions may be able to help you here.

    drop, take :: Int -> [a] -> [a]
    

    from these we could construct a function to do one step.

    takeNdropM :: Int -> Int -> [a] -> ([a], [a])
    takeNdropM n m list = (take n list, drop (n+m) list)
    

    and then we can use this to reduce our problem

    takeEveryNafterEveryM :: Int -> Int -> [a] -> [a]
    takeEveryNafterEveryM n m [] = []
    takeEveryNafterEveryM n m list = taken ++ takeEveryNafterEveryM n m rest
        where
            (taken, rest) = takeNdropM n m list
    
    *Main> takeEveryNafterEveryM 5 3 [1..20]
    [1,2,3,4,5,9,10,11,12,13,17,18,19,20]
    

    since this is not a primitive form of recursion, it is harder to express this as a simple fold.

    so a new folding function could be defined to fit your needs

    splitReduce :: ([a] -> ([a], [a])) -> [a] -> [a]
    splitReduce f []   = []
    splitReduce f list = left ++ splitReduce f right
        where
            (left, right) = f list
    

    then the definition of takeEveryNafterEveryM is simply

    takeEveryNafterEveryM2 n m = splitReduce (takeNdropM 5 3)
    

提交回复
热议问题