Haskell "transform" function -
i've written imagine common function in haskell, couldn't find implemented anywhere. want of better word i've called "transform".
what "transform" 3 arguments: list, , initial state , function takes element list, state, , produces element output list, , new state. output list same length input list.
it's kind of "scanl" if took state parameter, or "unfoldr" if feed list.
indeed, i've implemented function below, in 2 different ways have same result:
transform1 :: (b -> c -> (a, c)) -> c -> [b] -> [a] transform1 f init x = unfoldr f' (x, init) f' ((l:ls), accum) = let (r, new_accum) = f l accum in (r, (ls, new_accum)) f' ([], _) = nothing transform2 :: (b -> c -> (a, c)) -> c -> [b] -> [a] transform2 f init x = map fst $ tail $ scanl f' init' x f' (_,x) y = f y x init' = (undefined, init)
this sort of operation seems relatively common though, is, taking list , walking through state , producing new list, i'm wondering if there's function exists , i'm reinventing wheel. if so, i'll use that, if not, might package i've got (very) small library.
this almost, not data.list.mapaccuml
. difference mapaccuml
includes final state. got generalized traversable
.
mapaccuml :: traversable t => (a -> b -> (a, c)) -> -> t b -> (a, t c)
Comments
Post a Comment