Skip to content
This repository was archived by the owner on Feb 2, 2021. It is now read-only.

Commit dd68bd0

Browse files
Tom Hardingpaf31
authored andcommitted
Add mapWithAccum to FRP.Event (#14)
* Add `mapWithAccum` to FRP.Event The Event class now exports the `mapWithAccum` function. There was originally concern that this would cause a huge composition chain, and thus not be performant for events over a long period. However, I've expanded the point-free folding function definition, so it's hopefully now a bit clearer that it shouldn't happen. As always, though, @paf31, do tell me if I'm being ignorant! * Implement code review changes s/mapWithAccum/mapAccum/g, and actually remembered to export it... >_<
1 parent 0583024 commit dd68bd0

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

src/FRP/Event.purs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ module FRP.Event
44
, never
55
, filter
66
, mapMaybe
7+
, mapAccum
78
, count
89
, folded
910
, withLast
@@ -14,11 +15,13 @@ module FRP.Event
1415
) where
1516

1617
import Prelude
18+
1719
import Control.Alternative (class Alt, class Alternative, class Plus)
1820
import Control.Apply (lift2)
1921
import Control.Monad.Eff (Eff)
2022
import Data.Maybe (Maybe(..), fromJust, isJust)
2123
import Data.Monoid (class Monoid, mempty)
24+
import Data.Tuple (Tuple(..), snd)
2225
import FRP (FRP)
2326
import Partial.Unsafe (unsafePartial)
2427

@@ -72,6 +75,14 @@ foreign import applyImpl :: forall a b. Event (a -> b) -> Event a -> Event b
7275
-- | Fold over values received from some `Event`, creating a new `Event`.
7376
foreign import fold :: forall a b. (a -> b -> b) -> Event a -> b -> Event b
7477

78+
-- | Map over an event, but carry an accumulator value with you. This can be
79+
-- | pretty useful if, for example, you want to attach IDs to events:
80+
-- | `mapAccum (\x i -> Tuple (i + 1) (Tuple x i)) 0`.
81+
mapAccum :: forall a b c. (a -> b -> Tuple b c) -> Event a -> b -> Event c
82+
mapAccum f xs acc = mapMaybe snd
83+
$ fold (\a (Tuple b _) -> pure <$> f a b) xs
84+
$ Tuple acc Nothing
85+
7586
-- | Count the number of events received.
7687
count :: forall a. Event a -> Event Int
7788
count s = fold (\_ n -> n + 1) s 0

0 commit comments

Comments
 (0)