Skip to content

Commit f20d4e0

Browse files
devonhollowoodGabriella439
authored andcommitted
Add convenience functions (#332)
* Re-export (<&>) from Data.Functor * Add `reduce` function
1 parent 76224d9 commit f20d4e0

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/Turtle.hs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ module Turtle (
8787
, ExitCode(..)
8888
, IsString(..)
8989
, (&)
90+
, (<&>)
9091
) where
9192

9293
import Turtle.Format
@@ -163,3 +164,32 @@ infixl 1 &
163164
(&) :: a -> (a -> b) -> b
164165
x & f = f x
165166
#endif
167+
168+
#if __GLASGOW_HASKELL__ >= 821
169+
import Data.Functor ((<&>))
170+
#else
171+
-- | Flipped version of '<$>'.
172+
--
173+
-- @
174+
-- ('<&>') = 'flip' 'fmap'
175+
-- @
176+
--
177+
-- @since 4.11.0.0
178+
--
179+
-- ==== __Examples__
180+
-- Apply @(+1)@ to a list, a 'Data.Maybe.Just' and a 'Data.Either.Right':
181+
--
182+
-- >>> Just 2 <&> (+1)
183+
-- Just 3
184+
--
185+
-- >>> [1,2,3] <&> (+1)
186+
-- [2,3,4]
187+
--
188+
-- >>> Right 3 <&> (+1)
189+
-- Right 4
190+
--
191+
(<&>) :: Functor f => f a -> (a -> b) -> f b
192+
as <&> f = f <$> as
193+
194+
infixl 1 <&>
195+
#endif

src/Turtle/Shell.hs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ module Turtle.Shell (
6666
, foldIO
6767
, foldShell
6868
, fold
69+
, reduce
6970
, sh
7071
, view
7172

@@ -143,6 +144,16 @@ foldShell s f = liftIO (_foldShell s f)
143144
fold :: MonadIO io => Shell a -> Fold a b -> io b
144145
fold s f = foldIO s (Foldl.generalize f)
145146

147+
-- | Flipped version of 'fold'. Useful for reducing a stream of data
148+
--
149+
-- ==== __Example__
150+
-- Sum a `Shell` of numbers:
151+
--
152+
-- >>> select [1, 2, 3] & reduce Fold.sum
153+
-- 6
154+
reduce :: MonadIO io => Fold a b -> Shell a -> io b
155+
reduce = flip fold
156+
146157
-- | Run a `Shell` to completion, discarding any unused values
147158
sh :: MonadIO io => Shell a -> io ()
148159
sh s = fold s (pure ())

0 commit comments

Comments
 (0)