Question

I am trying to write a sort of scanl like function of type:

general_scanl' :: (a->b->a)->(a->b->[c])->a->[b]->[c]

The function is intended to output the same as the following two monstrosities:

general_scanl' f g x y = snd $ foldl' (\(p,q) r -> (f p r,q ++ g p r)) (x,[]) y

or,

general_scanl' f g x y = concat $ zipWith g (scanl f x y) y

The disadvantage of the first definition is that it contains a handwritten lambda.
The disadvantage of the second definition is that it accumulates a list of lists (scanl f x y) which isn't necessary...

My question: is there a cleaner way to define this function?

Many thanks,

Was it helpful?

Solution

You have

Prelude> let general_scanl2 f g z xs = concat $ zipWith g (scanl f z xs) xs
--                                                         :: [a]
Prelude> :t general_scanl2
general_scanl2 :: (a -> b -> a)        -- f
                  -> (a -> b -> [c])   -- g
                  -> a                 -- z
                  -> [b]               -- xs
                  -> [c]

Prelude Data.List> :t mapAccumL
mapAccumL :: (a -> b -> (a, y)) -> a -> [b] -> (a, [y])

So, another way to write this seems to be

import Data.List

g_scanl3 :: (a -> b -> a) -> (a -> b -> [c]) -> a -> [b] -> [c]
g_scanl3 f g z xs = concat . snd $ 
                      mapAccumL (\a b-> (f a b, g a b)) z xs
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top