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

[RFC] foldWhile #453

Open
ocramz opened this issue Nov 8, 2020 · 3 comments
Open

[RFC] foldWhile #453

ocramz opened this issue Nov 8, 2020 · 3 comments

Comments

@ocramz
Copy link
Contributor

ocramz commented Nov 8, 2020

A specialized version of mapAccumWhile that keeps folding as long as the function argument returns 'Right'

foldWhile :: (Monad m) => (a -> s -> Either s s) -> s -> C.ConduitT a o m s
foldWhile f = loop
  where
    loop !s = C.await >>= maybe (pure s) go
      where
        go a = either (return $!) loop $ f a s
@ocramz
Copy link
Contributor Author

ocramz commented Nov 8, 2020

I found a need for this while writing a family of stochastic gradient descent algorithms; the conduit processes one data point of type a at a time and stops accumulating state when a convergence or divergence criterion is met.

@snoyberg
Copy link
Owner

snoyberg commented Nov 8, 2020

Seems reasonable to me. Only complaint I can think of: it hides away information about whether it was an end-of-stream versus a Left value produced by f. It may make more sense to generalize a bit to:

foldWhile :: Monad m => (a -> s -> Either e s) -> s -> ConduitT a o m (Either e s)

Either with fmap (either id id) you recover the original behavior. Thoughts?

@ocramz
Copy link
Contributor Author

ocramz commented Nov 8, 2020

Indeed, your version of foldWhile is clearer. I'll prepare a PR!

@ocramz ocramz mentioned this issue Nov 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants