@@ -37,6 +37,7 @@ import qualified Text.XmlHtml.HTML.Meta as X
37
37
------------------------------------------------------------------------------
38
38
#if !MIN_VERSION_base(4,8,0)
39
39
import Data.Foldable (Foldable )
40
+ import Data.Monoid
40
41
#endif
41
42
import qualified Data.Foldable as Foldable
42
43
------------------------------------------------------------------------------
@@ -749,12 +750,31 @@ deferMany :: (Foldable f, Monad n)
749
750
=> (RuntimeSplice n a -> Splice n )
750
751
-> RuntimeSplice n (f a )
751
752
-> Splice n
752
- deferMany f getItems = do
753
+ deferMany = deferManyElse $ return mempty
754
+
755
+
756
+ ------------------------------------------------------------------------------
757
+ -- | A version of 'deferMany' which has a default splice to run in the case
758
+ -- when there are no elements in the given list.
759
+ deferManyElse :: (Foldable f , Monad n )
760
+ => Splice n
761
+ -> (RuntimeSplice n a -> Splice n )
762
+ -> RuntimeSplice n (f a )
763
+ -> Splice n
764
+ deferManyElse def f getItems = do
753
765
promise <- newEmptyPromise
754
766
chunks <- f $ getPromise promise
767
+ defaultChunk <- def
755
768
return $ yieldRuntime $ do
756
769
items <- getItems
757
- foldMapM (\ item -> putPromise promise item >> codeGen chunks) items
770
+ if nullGeneric items
771
+ then codeGen defaultChunk
772
+ else foldMapM (\ item -> putPromise promise item >>
773
+ codeGen chunks) items
774
+ where
775
+ -- Use this instead of null for compatibility with pre 4.8 base
776
+ nullGeneric = foldrGeneric (\ _ _ -> False ) True
777
+ foldrGeneric f' z t = appEndo (foldMap (Endo . f') t) z
758
778
759
779
760
780
------------------------------------------------------------------------------
@@ -773,6 +793,23 @@ defer pf n = do
773
793
return $ action `mappend` res
774
794
775
795
796
+ ------------------------------------------------------------------------------
797
+ -- | Much like 'either', takes a runtime computation and branches to the
798
+ -- respective splice depending on the runtime value.
799
+ deferEither :: Monad n
800
+ => (RuntimeSplice n a -> Splice n )
801
+ -> (RuntimeSplice n b -> Splice n )
802
+ -> RuntimeSplice n (Either a b ) -> Splice n
803
+ deferEither pfa pfb n = do
804
+ pa <- newEmptyPromise
805
+ pb <- newEmptyPromise
806
+ failureChunk <- pfa $ getPromise pa
807
+ successChunk <- pfb $ getPromise pb
808
+ return $ yieldRuntime $ n >>= either
809
+ (\ x -> putPromise pa x >> codeGen failureChunk)
810
+ (\ x -> putPromise pb x >> codeGen successChunk)
811
+
812
+
776
813
------------------------------------------------------------------------------
777
814
-- | A version of defer which applies a function on the runtime value.
778
815
deferMap :: Monad n
0 commit comments