Partial fold of a list in Haskell -
how apply fold functions finite number of times, instead of folding entire list? example, incomplete fold sum first 3 numbers, leaving rest untouched:
foldln 3 (+) [1..5] -- [6,4,5]
it seems simple fold on part of list, cons rest of list:
foldln :: int -> (a -> -> a) -> [a] -> [a] foldln n f xs = (foldl1 f $ take n xs) : drop n xs
result in repl:
*main> foldln 3 (+) [1..5] [6,4,5]
if worry taking , dropping same list double job, can rewrite splitat
:
foldln n f xs = (foldl1 f $ fst t) : snd t t = splitat n xs
note type of function, can't base fold on foldl
, because can't have list [[1,2,3],4,5,6]
in haskell.
Comments
Post a Comment