Haskell partial sum of a list error

后端 未结 3 1275
时光说笑
时光说笑 2021-01-20 19:32

I need to write a function in Haskell that sums the elements of a list until some specific elements stored in another list.

For example partial_add [1,2,3,4,5,

3条回答
  •  失恋的感觉
    2021-01-20 19:59

    Note: I am a bit confused by the count parameter since it is ignored in one of the recursive calls, where it is always passed as 0. It should be easy to add its behavior once it's more clear what it does.

    Another way to look at this is to first separate the second list* into sublists delimited by (and including) the elements of the first list and then to find the sums of each sublist:

    -- | A version of Data.List.splitOneOf that includes the delimiter
    splitOneOf' :: Eq a => [a] -> [a] -> [[a]]
    splitOneOf' _ [] = [[]]
    splitOneOf' delims (x:xs) | x `elem` delims = [x] : splitOneOf' delims xs
    splitOneOf' delims (x:xs) | otherwise = let (ys:yss) = splitOneOf' delims xs
                                            in (x:ys) : yss
    
    partialAdd :: (Eq a, Num a) => [a] -> [a] -> [a]
    partialAdd delims = map sum . splitOneOf' delims
    
    main :: IO ()
    main = print $ partialAdd [2,5] [1,2,3,4,5,6]
    

    gives

    [3,12,6]
    

    I think this is a nice example of "bottom up" programming in Haskell.

    * I reversed the argument order to match the order used by Data.List.Split.

提交回复
热议问题