Traversable to Traversable, crossing only the element with the specified index

I wonder if it is possible to build the following function

ix :: (Applicative a, Traversable t) => Int -> (v -> a v) -> (t v -> a (t v))

Uses purefor all elements except the i-th for which it is used v -> a v(bypass by value with the specified index).

I am basically trying to generalize the following function to all traversables. Or is it impossible? Traversable can always be converted to Zipper , and I thought it could be generalized.

idx _ _ []     = pure []
idx 0 f (x:xs) = (:xs) <$> f x
idx i f (x:xs) = (x:)  <$> idx (i - 1) f xs
+4
source share
1 answer

Here is a special attempt. I am sure there are more elegant options:

import Control.Applicative
import Control.Monad.State
import Data.Traversable as T

ix :: (Applicative a, Traversable t) => Int -> (v -> a v) -> (t v -> a (t v))
ix i f =
    sequenceA
  . flip evalState 0
  . T.mapM (\ x -> do
                     j <- get
                     put (j + 1)
                     if i == j then return (f x)
                               else return (pure x))
+3
source

All Articles