on develop help sign in
Merge pull request #70 from spl/distribute-list-over-dynamic

Add distributeListOverDynPure, export distributeMapOverDynPure

commit32c726afcb098062b00e4c2b20d0e78e5e0d5614 authorRyan Trinkle <ryan.trinkle@gmail.com> dateTue 18 Oct 2016, 10:22 (10 years ago) parenta63aba9893f3a3
1 file changed+18−7
src/Reflex/Dynamic.hs+18−7
src/Reflex/Dynamic.hs+18−7
@@ -39,6 +39,8 @@ module Reflex.Dynamic
3939 , traceDynWith
4040 , splitDynPure
4141 , distributeDMapOverDynPure
42+ , distributeMapOverDynPure
43+ , distributeListOverDynPure
4244 , Demux
4345 , demux
4446 , demuxed
@@ -151,16 +153,25 @@ switchPromptlyDyn de =
151153splitDynPure :: Reflex t => Dynamic t (a, b) -> (Dynamic t a, Dynamic t b)
152154splitDynPure d = (fmap fst d, fmap snd d)
153155
154−-- | Create a 'Dynamic' with a 'DMap' of values out of a 'DMap' of 'Dynamic'
155−-- values. The resulting 'Dynamic' will change whenever one of the input
156−-- 'Dynamic's changes.
157−--
158−-- This function's implementation is more efficient than simply using
159−-- 'zipDynWith' or applicative syntax to achieve the same result, especially for
160−-- maps with many elements.
156+-- | Convert a 'Map' with 'Dynamic' elements into a 'Dynamic' of a 'Map' with
157+-- non-'Dynamic' elements.
161158distributeMapOverDynPure :: (Reflex t, Ord k) => Map k (Dynamic t v) -> Dynamic t (Map k v)
162159distributeMapOverDynPure = fmap dmapToMap . distributeDMapOverDynPure . mapWithFunctorToDMap
163160
161+-- | Convert a list with 'Dynamic' elements into a 'Dynamic' of a list with
162+-- non-'Dynamic' elements, preserving the order of the elements.
163+distributeListOverDynPure :: Reflex t => [Dynamic t v] -> Dynamic t [v]
164+distributeListOverDynPure =
165+ fmap (map fromDSum . DMap.toAscList) .
166+ distributeDMapOverDynPure .
167+ DMap.fromDistinctAscList .
168+ zipWith toDSum [0..]
169+ where
170+ toDSum :: Int -> Dynamic t a -> DSum (Const2 Int a) (Dynamic t)
171+ toDSum k v = Const2 k :=> v
172+ fromDSum :: DSum (Const2 Int a) Identity -> a
173+ fromDSum (Const2 _ :=> Identity v) = v
174+
164175--TODO: Generalize this to functors other than Maps
165176-- | Combine a 'Dynamic' of a 'Map' of 'Dynamic's into a 'Dynamic'
166177-- with the current values of the 'Dynamic's in a map.