Haskell:按索引列表拆分列表

时间:2014-03-02 21:03:59

标签: haskell split functional-programming

我是函数式编程和学习Haskell的新手。我有一个索引列表和一个我想根据索引列表拆分的元素列表(按递增顺序排序)。

splitByIndices :: [a] -> [Int] -> [[a]]

我在考虑take indexlist[n]drop indexlist[n-1],但不知道如何使用foldl来实现它。请帮忙!谢谢!

示例:

splitByIndices [1,2,3,4,5] [1,2] = [1],[2],[3,4,5]

3 个答案:

答案 0 :(得分:4)

split包以名称splitPlaces提供此内容。

答案 1 :(得分:1)

我用foldr解决了这个问题,它有点复杂:

splitByIndices :: [String] -> [Int] -> [[String]]
splitByIndices input indexlist = foldr (\elem acc -> [fst $ splitAt elem $ head acc] ++ [snd $ splitAt elem $ head acc] ++ (tail acc)) [input] indexlist

答案 2 :(得分:1)

splitByIndices :: [a] -> [Int] -> [[a]]
splitByIndices xs is = go xs (zipWith subtract (0:is) is) where
    go [] _      = []
    go xs (i:is) = let (a, b) = splitAt i xs in a : go b is
    go xs _      = [xs]

当指数没有严格增加时,这当然会产生不正确的结果。您可以通过以下方式强制执行此条件:

import Data.List

enforce :: [Int] -> [Int]
enforce = map head . group . sort

然后您可以使用enforce is代替is