Skip to content

Support for Indexed Folds? #484

Open

Description

@HuwCampbell

Sorry if this is already addressed.

I'm in need of an ifoldl' function over text values, and I can't seem to find it.

ifoldl' :: forall a. (a -> Int -> Char -> a) -> a -> Text -> a

Lens combinators come close, but I don't think it's possible to make an instance of FoldableWithIndex for text?

Activity

  1. Lysxia commented on Feb 4, 2023

    @Lysxia
    Contributor

    I don't know if we want this, but note that you can define ifoldl' using Text.foldr or Text.foldl. Or if you have it for lists, you can compose it with Text.unpack.

    ifoldlText :: (Int -> r -> Char -> r) -> r -> Text -> r
    ifoldlText f r t = Text.foldr (\c k i x -> k (i+1) (f i x c)) (\_ x -> x) t 0 r
    

    Test example

    main :: IO ()
    main = do
      let f i x c = x ++ [(i, c)]
      print (ifoldlText f [] "hello")
      -- Output: [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
    
  2. HuwCampbell commented on Feb 5, 2023

    @HuwCampbell
    ContributorAuthor

    Thanks. I ended up rolling this:

    ifoldl' :: (Int -> b -> Char -> b) -> b -> Text -> b
    ifoldl' f z0 =
      go . stream
        where
      go (Stream next s0 _len) =
        loop 0 z0 s0
          where
        loop !ix !z !s =
          case next s of
            Done -> z
            Skip s' -> loop ix z s'
            Yield x s' -> loop (ix + 1) (f ix z x) s'

    I'm not sure if it actually fuses any better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions