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

OneOf? #68

Open
justinwoo opened this issue Nov 18, 2017 · 4 comments
Open

OneOf? #68

justinwoo opened this issue Nov 18, 2017 · 4 comments
Labels
status: needs more info This issue needs more info before any action can be done.

Comments

@justinwoo
Copy link

justinwoo commented Nov 18, 2017

Feels like we probably already have a oneOf function that can make sure that not all branches are evaluated at once (to ensure efficient as-needed parsing), since using alt naively can lead to really really slow decoding, but I honestly don't know where it is. Is there something I'm missing that already implements this?:

oneOf :: forall f a
   . Foldable f
  => f (Foreign -> F a)
  -> Foreign
  -> F a
oneOf f js = go (fromFoldable f) js
  where
    go (read : xs) js = do
      case runExcept (read js) of
        Right pv -> pure pv
        Left e -> do
          case runExcept (go xs js) of
            Right pv' -> pure pv'
            Left e' -> throwError (e <> e')
    go Nil _ = do
      throwError $ pure (ForeignError "No more parsers to attempt in oneOf")

If not, I could PR this, but feels like it probably exists as a simple combination of some operators.

@MonoidMusician
Copy link

This looks good! Perhaps you want to use foldl (or even foldl1?) instead, to avoid copying the list?

go prev next = case runExcept prev of
  Left e -> case runExcept (next js) of
    Left e' -> throwError (e <> e')
    r -> r
  r -> r

But yeah, it's hard ... we need laziness dreamy sigh

@paf31
Copy link
Contributor

paf31 commented Nov 18, 2017

If we had a lazy Either, we could use regular oneOf, right?

@MonoidMusician
Copy link

newtype Decoder = Decoder (Foreign -> F a) would probably work – just making the return type lazy would be hard to use, I think.

@paf31
Copy link
Contributor

paf31 commented Nov 18, 2017

Decoder does sound useful anyway.

@JordanMartinez JordanMartinez added the status: needs more info This issue needs more info before any action can be done. label Dec 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
status: needs more info This issue needs more info before any action can be done.
Projects
None yet
Development

No branches or pull requests

4 participants