Merge branch 'master' into type-nats
[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, online at
21 -- <http://www.soi.city.ac.uk/~ross/papers/Applicative.html>.
22 --
23 -- * /The Essence of the Iterator Pattern/,
24 -- by Jeremy Gibbons and Bruno Oliveira,
25 -- in /Mathematically-Structured Functional Programming/, 2006, and online at
26 -- <http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator>.
27 --
28 -- Note that the functions 'mapM' and 'sequence' generalize "Prelude"
29 -- functions of the same names from lists to any 'Traversable' functor.
30 -- To avoid ambiguity, either import the "Prelude" hiding these names
31 -- or qualify uses of these function names with an alias for this module.
32 --
33 -----------------------------------------------------------------------------
34
35 module Data.Traversable (
36 Traversable(..),
37 for,
38 forM,
39 mapAccumL,
40 mapAccumR,
41 fmapDefault,
42 foldMapDefault,
43 ) where
44
45 import Prelude hiding (mapM, sequence, foldr)
46 import qualified Prelude (mapM, foldr)
47 import Control.Applicative
48 import Data.Foldable (Foldable())
49 import Data.Monoid (Monoid)
50
51 #if defined(__GLASGOW_HASKELL__)
52 import GHC.Arr
53 #elif defined(__HUGS__)
54 import Hugs.Array
55 #elif defined(__NHC__)
56 import Array
57 #endif
58
59 -- | Functors representing data structures that can be traversed from
60 -- left to right.
61 --
62 -- Minimal complete definition: 'traverse' or 'sequenceA'.
63 --
64 -- Instances are similar to 'Functor', e.g. given a data type
65 --
66 -- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
67 --
68 -- a suitable instance would be
69 --
70 -- > instance Traversable Tree where
71 -- > traverse f Empty = pure Empty
72 -- > traverse f (Leaf x) = Leaf <$> f x
73 -- > traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r
74 --
75 -- This is suitable even for abstract types, as the laws for '<*>'
76 -- imply a form of associativity.
77 --
78 -- The superclass instances should satisfy the following:
79 --
80 -- * In the 'Functor' instance, 'fmap' should be equivalent to traversal
81 -- with the identity applicative functor ('fmapDefault').
82 --
83 -- * In the 'Foldable' instance, 'Data.Foldable.foldMap' should be
84 -- equivalent to traversal with a constant applicative functor
85 -- ('foldMapDefault').
86 --
87 class (Functor t, Foldable t) => Traversable t where
88 -- | Map each element of a structure to an action, evaluate
89 -- these actions from left to right, and collect the results.
90 traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
91 traverse f = sequenceA . fmap f
92
93 -- | Evaluate each action in the structure from left to right,
94 -- and collect the results.
95 sequenceA :: Applicative f => t (f a) -> f (t a)
96 sequenceA = traverse id
97
98 -- | Map each element of a structure to a monadic action, evaluate
99 -- these actions from left to right, and collect the results.
100 mapM :: Monad m => (a -> m b) -> t a -> m (t b)
101 mapM f = unwrapMonad . traverse (WrapMonad . f)
102
103 -- | Evaluate each monadic action in the structure from left to right,
104 -- and collect the results.
105 sequence :: Monad m => t (m a) -> m (t a)
106 sequence = mapM id
107
108 -- instances for Prelude types
109
110 instance Traversable Maybe where
111 traverse _ Nothing = pure Nothing
112 traverse f (Just x) = Just <$> f x
113
114 instance Traversable [] where
115 {-# INLINE traverse #-} -- so that traverse can fuse
116 traverse f = Prelude.foldr cons_f (pure [])
117 where cons_f x ys = (:) <$> f x <*> ys
118
119 mapM = Prelude.mapM
120
121 instance Ix i => Traversable (Array i) where
122 traverse f arr = listArray (bounds arr) `fmap` traverse f (elems arr)
123
124 -- general functions
125
126 -- | 'for' is 'traverse' with its arguments flipped.
127 for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)
128 {-# INLINE for #-}
129 for = flip traverse
130
131 -- | 'forM' is 'mapM' with its arguments flipped.
132 forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
133 {-# INLINE forM #-}
134 forM = flip mapM
135
136 -- left-to-right state transformer
137 newtype StateL s a = StateL { runStateL :: s -> (s, a) }
138
139 instance Functor (StateL s) where
140 fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v)
141
142 instance Applicative (StateL s) where
143 pure x = StateL (\ s -> (s, x))
144 StateL kf <*> StateL kv = StateL $ \ s ->
145 let (s', f) = kf s
146 (s'', v) = kv s'
147 in (s'', f v)
148
149 -- |The 'mapAccumL' function behaves like a combination of 'fmap'
150 -- and 'foldl'; it applies a function to each element of a structure,
151 -- passing an accumulating parameter from left to right, and returning
152 -- a final value of this accumulator together with the new structure.
153 mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
154 mapAccumL f s t = runStateL (traverse (StateL . flip f) t) s
155
156 -- right-to-left state transformer
157 newtype StateR s a = StateR { runStateR :: s -> (s, a) }
158
159 instance Functor (StateR s) where
160 fmap f (StateR k) = StateR $ \ s -> let (s', v) = k s in (s', f v)
161
162 instance Applicative (StateR s) where
163 pure x = StateR (\ s -> (s, x))
164 StateR kf <*> StateR kv = StateR $ \ s ->
165 let (s', v) = kv s
166 (s'', f) = kf s'
167 in (s'', f v)
168
169 -- |The 'mapAccumR' function behaves like a combination of 'fmap'
170 -- and 'foldr'; it applies a function to each element of a structure,
171 -- passing an accumulating parameter from right to left, and returning
172 -- a final value of this accumulator together with the new structure.
173 mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
174 mapAccumR f s t = runStateR (traverse (StateR . flip f) t) s
175
176 -- | This function may be used as a value for `fmap` in a `Functor`
177 -- instance, provided that 'traverse' is defined. (Using
178 -- `fmapDefault` with a `Traversable` instance defined only by
179 -- 'sequenceA' will result in infinite recursion.)
180 fmapDefault :: Traversable t => (a -> b) -> t a -> t b
181 {-# INLINE fmapDefault #-}
182 fmapDefault f = getId . traverse (Id . f)
183
184 -- | This function may be used as a value for `Data.Foldable.foldMap`
185 -- in a `Foldable` instance.
186 foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m
187 foldMapDefault f = getConst . traverse (Const . f)
188
189 -- local instances
190
191 newtype Id a = Id { getId :: a }
192
193 instance Functor Id where
194 fmap f (Id x) = Id (f x)
195
196 instance Applicative Id where
197 pure = Id
198 Id f <*> Id x = Id (f x)
199