|
1 | | -module Data.Traversable where |
| 1 | +module Data.Traversable |
| 2 | + ( Traversable |
| 3 | + , traverse |
| 4 | + , sequence |
| 5 | + , for |
| 6 | + , zipWithA |
| 7 | + , mapAccumL |
| 8 | + , mapAccumR |
| 9 | + ) where |
2 | 10 |
|
3 | 11 | import Prelude |
4 | 12 | import Data.Array (zipWith) |
@@ -49,3 +57,43 @@ for x f = traverse f x |
49 | 57 | zipWithA :: forall m a b c. (Applicative m) => (a -> b -> m c) -> [a] -> [b] -> m [c] |
50 | 58 | zipWithA f xs ys = sequence (zipWith f xs ys) |
51 | 59 |
|
| 60 | +newtype StateL s a = StateL (s -> Tuple s a) |
| 61 | + |
| 62 | +stateL :: forall s a. StateL s a -> s -> Tuple s a |
| 63 | +stateL (StateL k) = k |
| 64 | + |
| 65 | +instance functorStateL :: Functor (StateL s) where |
| 66 | + (<$>) f k = StateL $ \s -> case stateL k s of |
| 67 | + Tuple s1 a -> Tuple s1 (f a) |
| 68 | + |
| 69 | +instance applyStateL :: Apply (StateL s) where |
| 70 | + (<*>) f x = StateL $ \s -> case stateL f s of |
| 71 | + Tuple s1 f' -> case stateL x s1 of |
| 72 | + Tuple s2 x' -> Tuple s2 (f' x') |
| 73 | + |
| 74 | +instance applicativeStateL :: Applicative (StateL s) where |
| 75 | + pure a = StateL $ \s -> Tuple s a |
| 76 | + |
| 77 | +mapAccumL :: forall a b s f. (Traversable f) => (s -> a -> Tuple s b) -> s -> f a -> Tuple s (f b) |
| 78 | +mapAccumL f s0 xs = stateL (traverse (\a -> StateL $ \s -> f s a) xs) s0 |
| 79 | + |
| 80 | +newtype StateR s a = StateR (s -> Tuple s a) |
| 81 | + |
| 82 | +stateR :: forall s a. StateR s a -> s -> Tuple s a |
| 83 | +stateR (StateR k) = k |
| 84 | + |
| 85 | +instance functorStateR :: Functor (StateR s) where |
| 86 | + (<$>) f k = StateR $ \s -> case stateR k s of |
| 87 | + Tuple s1 a -> Tuple s1 (f a) |
| 88 | + |
| 89 | +instance applyStateR :: Apply (StateR s) where |
| 90 | + (<*>) f x = StateR $ \s -> case stateR x s of |
| 91 | + Tuple s1 x' -> case stateR f s1 of |
| 92 | + Tuple s2 f' -> Tuple s2 (f' x') |
| 93 | + |
| 94 | +instance applicativeStateR :: Applicative (StateR s) where |
| 95 | + pure a = StateR $ \s -> Tuple s a |
| 96 | + |
| 97 | +mapAccumR :: forall a b s f. (Traversable f) => (s -> a -> Tuple s b) -> s -> f a -> Tuple s (f b) |
| 98 | +mapAccumR f s0 xs = stateR (traverse (\a -> StateR $ \s -> f s a) xs) s0 |
| 99 | + |
0 commit comments