Haskell Transform Function

I wrote what, in my opinion, will be a common function in Haskell, but I could not find it implemented anywhere. Because of a better word, I called it "transform."

Three arguments are used in the "conversion": a list and an initial state, as well as a function that takes an element from a list, a state and creates an element for the output list, and a new state. The output list is the same length as the input list.

This is similar to "scanl" if it also took a status parameter or, for example, "unfoldr" if you can list it.

In fact, I implemented this function below in two different ways that have the same result:

transform1 :: (b -> c -> (a, c)) -> c -> [b] -> [a]
transform1 f init x = unfoldr f' (x, init)
  where
    f'  ((l:ls), accum) = let (r, new_accum) = f l accum in Just (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 where
  f' (_,x) y = f y x
  init' = (undefined, init)

, .., , , , , , , , , , () .

+4
1

, Data.List.mapAccumL. , mapAccumL . Traversable.

mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
+6

Source: https://habr.com/ru/post/1612769/


All Articles