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

Combinators should be more strict #109

Open
tibbe opened this issue Oct 9, 2015 · 1 comment
Open

Combinators should be more strict #109

tibbe opened this issue Oct 9, 2015 · 1 comment

Comments

@tibbe
Copy link
Member

tibbe commented Oct 9, 2015

I found and fixed lots of small space leaks in cassava but rewriting several of the combinators like so:

-- | Specialized version of 'sepBy1'' which is faster due to not
-- accepting an arbitrary separator.
sepByDelim1' :: AL.Parser a
             -> Word8  -- ^ Field delimiter
             -> AL.Parser [a]
sepByDelim1' p !delim = liftM2' (:) p loop
  where
    loop = do
        mb <- A.peekWord8
        case mb of
            Just b | b == delim -> liftM2' (:) (A.anyWord8 *> p) loop
            _                   -> pure []
{-# INLINE sepByDelim1' #-}

(Ignore the use of peekWord8 instead of <|>, that's an optimization specific to my case.)

Note the use of liftM2' instead of (:) <$> (A.anyWord8 *> p) <*> loop. Without liftM2' we're building up a thunk in the list. This thunk will always be evaluated when we eventually run the parser so creating it here is unnecessary and wastes space. I would guess that (almost) all uses of <$> and <*> should be replaced by strict versions.

@bgamari
Copy link
Collaborator

bgamari commented Sep 15, 2016

One notable example of this is in the Alternative instance for Parser, which defines some with <$>. I don't see too many others though.

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