on master help sign in
Implement fromFoldMaybe
commit15a0629e8b66ee778fdd715d49b6e5e6fd04a983 authorRanjeet Kumar Ranjan <ranjeetr@composewell.com> dateMon 23 May 2022, 12:03 (4 years ago) parentfc86706
1 file changed+38
core/src/Streamly/Internal/Data/Parser/ParserD.hs+38
core/src/Streamly/Internal/Data/Parser/ParserD.hs+38
@@ -28,6 +28,7 @@ module Streamly.Internal.Data.Parser.ParserD
2828 -- First order parsers
2929 -- * Accumulators
3030 , fromFold
31+ , fromFoldMaybe
3132 , fromPure
3233 , fromEffect
3334 , die
@@ -297,6 +298,43 @@ fromFold (Fold fstep finitial fextract) = Parser step initial fextract
297298 FL.Partial s1 -> Partial 0 s1
298299 FL.Done b -> Done 0 b
299300
301+-- | Convert Maybe returning folds to error returning parsers.
302+--
303+-- /Pre-release/
304+--
305+{-# INLINE fromFoldMaybe #-}
306+fromFoldMaybe :: MonadThrow m => Fold m a (Maybe b) -> Parser m a b
307+fromFoldMaybe (Fold fstep finitial fextract) = Parser step initial extract
308+ where
309+
310+ errMsg = "Parse Error!"
311+
312+ initial = do
313+ res <- finitial
314+ return
315+ $ case res of
316+ FL.Partial s1 -> IPartial s1
317+ FL.Done b ->
318+ case b of
319+ Just x -> IDone x
320+ Nothing -> IError errMsg
321+
322+ step s a = do
323+ res <- fstep s a
324+ return
325+ $ case res of
326+ FL.Partial s1 -> Partial 0 s1
327+ FL.Done b ->
328+ case b of
329+ Just x -> Done 0 x
330+ Nothing -> Error errMsg
331+
332+ extract s = do
333+ res <- fextract s
334+ case res of
335+ Just x -> return x
336+ Nothing -> throwM $ ParseError errMsg
337+
300338-------------------------------------------------------------------------------
301339-- Failing Parsers
302340-------------------------------------------------------------------------------