Merge branch 'master' of http://darcs.haskell.org//packages/base
[ghc.git] / libraries / base / Data / Traversable.hs
1 {-# LANGUAGE Trustworthy #-}
2 {-# LANGUAGE CPP #-}
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 Prelude hiding (mapM, sequence, foldr)
55 import qualified Prelude (mapM, foldr)
56 import Control.Applicative
57 import Data.Foldable (Foldable())
58 import Data.Monoid (Monoid)
59
60 #if defined(__GLASGOW_HASKELL__)
61 import GHC.Arr
62 #elif defined(__HUGS__)
63 import Hugs.Array
64 #elif defined(__NHC__)
65 import Array
66 #endif
67
68 -- | Functors representing data structures that can be traversed from
69 -- left to right.
70 --
71 -- Minimal complete definition: 'traverse' or 'sequenceA'.
72 --
73 -- A definition of 'traverse' must satisfy the following laws:
74 --
75 -- [/naturality/]
76 -- @t . 'traverse' f = 'traverse' (t . f)@
77 -- for every applicative transformation @t@
78 --
79 -- [/identity/]
80 -- @'traverse' Identity = Identity@
81 --
82 -- [/composition/]
83 -- @'traverse' (Compose . 'fmap' g . f) = Compose . 'fmap' ('traverse' g) . 'traverse' f@
84 --
85 -- A definition of 'sequenceA' must satisfy the following laws:
86 --
87 -- [/naturality/]
88 -- @t . 'sequenceA' = 'sequenceA' . 'fmap' t@
89 -- for every applicative transformation @t@
90 --
91 -- [/identity/]
92 -- @'sequenceA' . 'fmap' Identity = Identity@
93 --
94 -- [/composition/]
95 -- @'sequenceA' . 'fmap' Compose = Compose . 'fmap' 'sequenceA' . 'sequenceA'@
96 --
97 -- where an /applicative transformation/ is a function
98 --
99 -- @t :: (Applicative f, Applicative g) => f a -> g a@
100 --
101 -- preserving the 'Applicative' operations, i.e.
102 --
103 -- * @t ('pure' x) = 'pure' x@
104 --
105 -- * @t (x '<*>' y) = t x '<*>' t y@
106 --
107 -- and the identity functor @Identity@ and composition of functors @Compose@
108 -- are defined as
109 --
110 -- > newtype Identity a = Identity a
111 -- >
112 -- > instance Functor Identity where
113 -- > fmap f (Identity x) = Identity (f x)
114 -- >
115 -- > instance Applicative Indentity where
116 -- > pure x = Identity x
117 -- > Identity f <*> Identity x = Identity (f x)
118 -- >
119 -- > newtype Compose f g a = Compose (f (g a))
120 -- >
121 -- > instance (Functor f, Functor g) => Functor (Compose f g) where
122 -- > fmap f (Compose x) = Compose (fmap (fmap f) x)
123 -- >
124 -- > instance (Applicative f, Applicative g) => Applicative (Compose f g) where
125 -- > pure x = Compose (pure (pure x))
126 -- > Compose f <*> Compose x = Compose ((<*>) <$> f <*> x)
127 --
128 -- (The naturality law is implied by parametricity.)
129 --
130 -- Instances are similar to 'Functor', e.g. given a data type
131 --
132 -- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
133 --
134 -- a suitable instance would be
135 --
136 -- > instance Traversable Tree where
137 -- > traverse f Empty = pure Empty
138 -- > traverse f (Leaf x) = Leaf <$> f x
139 -- > traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r
140 --
141 -- This is suitable even for abstract types, as the laws for '<*>'
142 -- imply a form of associativity.
143 --
144 -- The superclass instances should satisfy the following:
145 --
146 -- * In the 'Functor' instance, 'fmap' should be equivalent to traversal
147 -- with the identity applicative functor ('fmapDefault').
148 --
149 -- * In the 'Foldable' instance, 'Data.Foldable.foldMap' should be
150 -- equivalent to traversal with a constant applicative functor
151 -- ('foldMapDefault').
152 --
153 class (Functor t, Foldable t) => Traversable t where
154 -- | Map each element of a structure to an action, evaluate
155 -- these actions from left to right, and collect the results.
156 traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
157 traverse f = sequenceA . fmap f
158
159 -- | Evaluate each action in the structure from left to right,
160 -- and collect the results.
161 sequenceA :: Applicative f => t (f a) -> f (t a)
162 sequenceA = traverse id
163
164 -- | Map each element of a structure to a monadic action, evaluate
165 -- these actions from left to right, and collect the results.
166 mapM :: Monad m => (a -> m b) -> t a -> m (t b)
167 mapM f = unwrapMonad . traverse (WrapMonad . f)
168
169 -- | Evaluate each monadic action in the structure from left to right,
170 -- and collect the results.
171 sequence :: Monad m => t (m a) -> m (t a)
172 sequence = mapM id
173
174 -- instances for Prelude types
175
176 instance Traversable Maybe where
177 traverse _ Nothing = pure Nothing
178 traverse f (Just x) = Just <$> f x
179
180 instance Traversable [] where
181 {-# INLINE traverse #-} -- so that traverse can fuse
182 traverse f = Prelude.foldr cons_f (pure [])
183 where cons_f x ys = (:) <$> f x <*> ys
184
185 mapM = Prelude.mapM
186
187 instance Ix i => Traversable (Array i) where
188 traverse f arr = listArray (bounds arr) `fmap` traverse f (elems arr)
189
190 -- general functions
191
192 -- | 'for' is 'traverse' with its arguments flipped.
193 for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)
194 {-# INLINE for #-}
195 for = flip traverse
196
197 -- | 'forM' is 'mapM' with its arguments flipped.
198 forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
199 {-# INLINE forM #-}
200 forM = flip mapM
201
202 -- left-to-right state transformer
203 newtype StateL s a = StateL { runStateL :: s -> (s, a) }
204
205 instance Functor (StateL s) where
206 fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v)
207
208 instance Applicative (StateL s) where
209 pure x = StateL (\ s -> (s, x))
210 StateL kf <*> StateL kv = StateL $ \ s ->
211 let (s', f) = kf s
212 (s'', v) = kv s'
213 in (s'', f v)
214
215 -- |The 'mapAccumL' function behaves like a combination of 'fmap'
216 -- and 'foldl'; it applies a function to each element of a structure,
217 -- passing an accumulating parameter from left to right, and returning
218 -- a final value of this accumulator together with the new structure.
219 mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
220 mapAccumL f s t = runStateL (traverse (StateL . flip f) t) s
221
222 -- right-to-left state transformer
223 newtype StateR s a = StateR { runStateR :: s -> (s, a) }
224
225 instance Functor (StateR s) where
226 fmap f (StateR k) = StateR $ \ s -> let (s', v) = k s in (s', f v)
227
228 instance Applicative (StateR s) where
229 pure x = StateR (\ s -> (s, x))
230 StateR kf <*> StateR kv = StateR $ \ s ->
231 let (s', v) = kv s
232 (s'', f) = kf s'
233 in (s'', f v)
234
235 -- |The 'mapAccumR' function behaves like a combination of 'fmap'
236 -- and 'foldr'; it applies a function to each element of a structure,
237 -- passing an accumulating parameter from right to left, and returning
238 -- a final value of this accumulator together with the new structure.
239 mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
240 mapAccumR f s t = runStateR (traverse (StateR . flip f) t) s
241
242 -- | This function may be used as a value for `fmap` in a `Functor`
243 -- instance, provided that 'traverse' is defined. (Using
244 -- `fmapDefault` with a `Traversable` instance defined only by
245 -- 'sequenceA' will result in infinite recursion.)
246 fmapDefault :: Traversable t => (a -> b) -> t a -> t b
247 {-# INLINE fmapDefault #-}
248 fmapDefault f = getId . traverse (Id . f)
249
250 -- | This function may be used as a value for `Data.Foldable.foldMap`
251 -- in a `Foldable` instance.
252 foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m
253 foldMapDefault f = getConst . traverse (Const . f)
254
255 -- local instances
256
257 newtype Id a = Id { getId :: a }
258
259 instance Functor Id where
260 fmap f (Id x) = Id (f x)
261
262 instance Applicative Id where
263 pure = Id
264 Id f <*> Id x = Id (f x)
265