Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Indexed Folds? #484

Open
HuwCampbell opened this issue Dec 31, 2022 · 2 comments
Open

Support for Indexed Folds? #484

HuwCampbell opened this issue Dec 31, 2022 · 2 comments
Labels
feature request question Requires more investigation

Comments

@HuwCampbell
Copy link
Contributor

HuwCampbell commented Dec 31, 2022

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?

@Lysxia
Copy link
Contributor

Lysxia commented Feb 4, 2023

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')]

@Lysxia Lysxia added feature request question Requires more investigation labels Feb 4, 2023
@HuwCampbell
Copy link
Contributor Author

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
Labels
feature request question Requires more investigation
Projects
None yet
Development

No branches or pull requests

2 participants