Move `mapM` and `sequence` to GHC.Base and break import-cycles
[ghc.git] / libraries / base / Data / Traversable.hs
1 {-# LANGUAGE NoImplicitPrelude #-}
2 {-# LANGUAGE Trustworthy #-}
3
4 -----------------------------------------------------------------------------
5 -- |
6 -- Module : Data.Traversable
7 -- Copyright : Conor McBride and Ross Paterson 2005
8 -- License : BSD-style (see the LICENSE file in the distribution)
9 --
10 -- Maintainer : libraries@haskell.org
11 -- Stability : experimental
12 -- Portability : portable
13 --
14 -- Class of data structures that can be traversed from left to right,
15 -- performing an action on each element.
16 --
17 -- See also
18 --
19 -- * \"Applicative Programming with Effects\",
20 -- by Conor McBride and Ross Paterson,
21 -- /Journal of Functional Programming/ 18:1 (2008) 1-13, online at
22 -- <http://www.soi.city.ac.uk/~ross/papers/Applicative.html>.
23 --
24 -- * \"The Essence of the Iterator Pattern\",
25 -- by Jeremy Gibbons and Bruno Oliveira,
26 -- in /Mathematically-Structured Functional Programming/, 2006, online at
27 -- <http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator>.
28 --
29 -- * \"An Investigation of the Laws of Traversals\",
30 -- by Mauro Jaskelioff and Ondrej Rypacek,
31 -- in /Mathematically-Structured Functional Programming/, 2012, online at
32 -- <http://arxiv.org/pdf/1202.2919>.
33 --
34 -- Note that the functions 'mapM' and 'sequence' generalize "Prelude"
35 -- functions of the same names from lists to any 'Traversable' functor.
36 -- To avoid ambiguity, either import the "Prelude" hiding these names
37 -- or qualify uses of these function names with an alias for this module.
38 --
39 -----------------------------------------------------------------------------
40
41 module Data.Traversable (
42 -- * The 'Traversable' class
43 Traversable(..),
44 -- * Utility functions
45 for,
46 forM,
47 mapAccumL,
48 mapAccumR,
49 -- * General definitions for superclass methods
50 fmapDefault,
51 foldMapDefault,
52 ) where
53
54 import Control.Applicative ( Const(..), WrappedMonad(..) )
55 import Data.Either ( Either(..) )
56 import Data.Foldable ( Foldable )
57 import Data.Functor
58 import Data.Proxy ( Proxy(..) )
59
60 import GHC.Arr
61 import GHC.Base ( Applicative(..), Monad(..), Monoid, Maybe(..),
62 ($), (.), id, flip )
63 import qualified GHC.Base as Monad ( mapM )
64 import qualified GHC.List as List ( foldr )
65
66 -- | Functors representing data structures that can be traversed from
67 -- left to right.
68 --
69 -- Minimal complete definition: 'traverse' or 'sequenceA'.
70 --
71 -- A definition of 'traverse' must satisfy the following laws:
72 --
73 -- [/naturality/]
74 -- @t . 'traverse' f = 'traverse' (t . f)@
75 -- for every applicative transformation @t@
76 --
77 -- [/identity/]
78 -- @'traverse' Identity = Identity@
79 --
80 -- [/composition/]
81 -- @'traverse' (Compose . 'fmap' g . f) = Compose . 'fmap' ('traverse' g) . 'traverse' f@
82 --
83 -- A definition of 'sequenceA' must satisfy the following laws:
84 --
85 -- [/naturality/]
86 -- @t . 'sequenceA' = 'sequenceA' . 'fmap' t@
87 -- for every applicative transformation @t@
88 --
89 -- [/identity/]
90 -- @'sequenceA' . 'fmap' Identity = Identity@
91 --
92 -- [/composition/]
93 -- @'sequenceA' . 'fmap' Compose = Compose . 'fmap' 'sequenceA' . 'sequenceA'@
94 --
95 -- where an /applicative transformation/ is a function
96 --
97 -- @t :: (Applicative f, Applicative g) => f a -> g a@
98 --
99 -- preserving the 'Applicative' operations, i.e.
100 --
101 -- * @t ('pure' x) = 'pure' x@
102 --
103 -- * @t (x '<*>' y) = t x '<*>' t y@
104 --
105 -- and the identity functor @Identity@ and composition of functors @Compose@
106 -- are defined as
107 --
108 -- > newtype Identity a = Identity a
109 -- >
110 -- > instance Functor Identity where
111 -- > fmap f (Identity x) = Identity (f x)
112 -- >
113 -- > instance Applicative Indentity where
114 -- > pure x = Identity x
115 -- > Identity f <*> Identity x = Identity (f x)
116 -- >
117 -- > newtype Compose f g a = Compose (f (g a))
118 -- >
119 -- > instance (Functor f, Functor g) => Functor (Compose f g) where
120 -- > fmap f (Compose x) = Compose (fmap (fmap f) x)
121 -- >
122 -- > instance (Applicative f, Applicative g) => Applicative (Compose f g) where
123 -- > pure x = Compose (pure (pure x))
124 -- > Compose f <*> Compose x = Compose ((<*>) <$> f <*> x)
125 --
126 -- (The naturality law is implied by parametricity.)
127 --
128 -- Instances are similar to 'Functor', e.g. given a data type
129 --
130 -- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
131 --
132 -- a suitable instance would be
133 --
134 -- > instance Traversable Tree where
135 -- > traverse f Empty = pure Empty
136 -- > traverse f (Leaf x) = Leaf <$> f x
137 -- > traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r
138 --
139 -- This is suitable even for abstract types, as the laws for '<*>'
140 -- imply a form of associativity.
141 --
142 -- The superclass instances should satisfy the following:
143 --
144 -- * In the 'Functor' instance, 'fmap' should be equivalent to traversal
145 -- with the identity applicative functor ('fmapDefault').
146 --
147 -- * In the 'Foldable' instance, 'Data.Foldable.foldMap' should be
148 -- equivalent to traversal with a constant applicative functor
149 -- ('foldMapDefault').
150 --
151 class (Functor t, Foldable t) => Traversable t where
152 -- | Map each element of a structure to an action, evaluate
153 -- these actions from left to right, and collect the results.
154 traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
155 traverse f = sequenceA . fmap f
156
157 -- | Evaluate each action in the structure from left to right,
158 -- and collect the results.
159 sequenceA :: Applicative f => t (f a) -> f (t a)
160 sequenceA = traverse id
161
162 -- | Map each element of a structure to a monadic action, evaluate
163 -- these actions from left to right, and collect the results.
164 mapM :: Monad m => (a -> m b) -> t a -> m (t b)
165 mapM f = unwrapMonad . traverse (WrapMonad . f)
166
167 -- | Evaluate each monadic action in the structure from left to right,
168 -- and collect the results.
169 sequence :: Monad m => t (m a) -> m (t a)
170 sequence = mapM id
171 {-# MINIMAL traverse | sequenceA #-}
172
173 -- instances for Prelude types
174
175 instance Traversable Maybe where
176 traverse _ Nothing = pure Nothing
177 traverse f (Just x) = Just <$> f x
178
179 instance Traversable [] where
180 {-# INLINE traverse #-} -- so that traverse can fuse
181 traverse f = List.foldr cons_f (pure [])
182 where cons_f x ys = (:) <$> f x <*> ys
183
184 mapM = Monad.mapM
185
186 instance Traversable (Either a) where
187 traverse _ (Left x) = pure (Left x)
188 traverse f (Right y) = Right <$> f y
189
190 instance Traversable ((,) a) where
191 traverse f (x, y) = (,) x <$> f y
192
193 instance Ix i => Traversable (Array i) where
194 traverse f arr = listArray (bounds arr) `fmap` traverse f (elems arr)
195
196 instance Traversable Proxy where
197 traverse _ _ = pure Proxy
198 {-# INLINE traverse #-}
199 sequenceA _ = pure Proxy
200 {-# INLINE sequenceA #-}
201 mapM _ _ = return Proxy
202 {-# INLINE mapM #-}
203 sequence _ = return Proxy
204 {-# INLINE sequence #-}
205
206 instance Traversable (Const m) where
207 traverse _ (Const m) = pure $ Const m
208
209 -- general functions
210
211 -- | 'for' is 'traverse' with its arguments flipped.
212 for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)
213 {-# INLINE for #-}
214 for = flip traverse
215
216 -- | 'forM' is 'mapM' with its arguments flipped.
217 forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
218 {-# INLINE forM #-}
219 forM = flip mapM
220
221 -- left-to-right state transformer
222 newtype StateL s a = StateL { runStateL :: s -> (s, a) }
223
224 instance Functor (StateL s) where
225 fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v)
226
227 instance Applicative (StateL s) where
228 pure x = StateL (\ s -> (s, x))
229 StateL kf <*> StateL kv = StateL $ \ s ->
230 let (s', f) = kf s
231 (s'', v) = kv s'
232 in (s'', f v)
233
234 -- |The 'mapAccumL' function behaves like a combination of 'fmap'
235 -- and 'foldl'; it applies a function to each element of a structure,
236 -- passing an accumulating parameter from left to right, and returning
237 -- a final value of this accumulator together with the new structure.
238 mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
239 mapAccumL f s t = runStateL (traverse (StateL . flip f) t) s
240
241 -- right-to-left state transformer
242 newtype StateR s a = StateR { runStateR :: s -> (s, a) }
243
244 instance Functor (StateR s) where
245 fmap f (StateR k) = StateR $ \ s -> let (s', v) = k s in (s', f v)
246
247 instance Applicative (StateR s) where
248 pure x = StateR (\ s -> (s, x))
249 StateR kf <*> StateR kv = StateR $ \ s ->
250 let (s', v) = kv s
251 (s'', f) = kf s'
252 in (s'', f v)
253
254 -- |The 'mapAccumR' function behaves like a combination of 'fmap'
255 -- and 'foldr'; it applies a function to each element of a structure,
256 -- passing an accumulating parameter from right to left, and returning
257 -- a final value of this accumulator together with the new structure.
258 mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
259 mapAccumR f s t = runStateR (traverse (StateR . flip f) t) s
260
261 -- | This function may be used as a value for `fmap` in a `Functor`
262 -- instance, provided that 'traverse' is defined. (Using
263 -- `fmapDefault` with a `Traversable` instance defined only by
264 -- 'sequenceA' will result in infinite recursion.)
265 fmapDefault :: Traversable t => (a -> b) -> t a -> t b
266 {-# INLINE fmapDefault #-}
267 fmapDefault f = getId . traverse (Id . f)
268
269 -- | This function may be used as a value for `Data.Foldable.foldMap`
270 -- in a `Foldable` instance.
271 foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m
272 foldMapDefault f = getConst . traverse (Const . f)
273
274 -- local instances
275
276 newtype Id a = Id { getId :: a }
277
278 instance Functor Id where
279 fmap f (Id x) = Id (f x)
280
281 instance Applicative Id where
282 pure = Id
283 Id f <*> Id x = Id (f x)
284