/
Class.purs
51 lines (41 loc) · 1.81 KB
/
Class.purs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
-- | This module defines the `ComonadTraced` type class and its instances.
module Control.Comonad.Traced.Class where
import Prelude
import Control.Comonad (class Comonad, extract)
import Control.Comonad.Traced.Trans (TracedT(..))
import Data.Monoid (class Monoid)
import Data.Tuple (Tuple(..))
-- | The `ComonadTraced` type class represents those monads which support relative (monoidal)
-- | position information via `track`.
-- |
-- | - `track` extracts a value at the specified relative position.
-- |
-- | An implementation is provided for `TracedT`.
-- |
-- | Laws:
-- |
-- | - `track mempty = extract`
-- | - `track s <<= track t x = track (s <> t) x`
-- |
-- | For example:
-- |
-- | ```purescript
-- | blur :: forall w. (ComonadTraced (Additive Number) w) -> w Number -> w Number
-- | blur = extend \r -> (track (Additive (-1)) r + track (Additive 1) r) / 2
-- | ```
class Comonad w <= ComonadTraced t w | w -> t where
track :: forall a. t -> w a -> a
-- | Extracts a value at a relative position which depends on the current value.
tracks :: forall w a t. ComonadTraced t w => (a -> t) -> w a -> a
tracks f w = track (f $ extract w) w
-- | Get the current position.
listen :: forall w a t. Functor w => TracedT t w a -> TracedT t w (Tuple a t)
listen (TracedT tr) = TracedT ((\f t -> Tuple (f t) t) <$> tr)
-- | Get a value which depends on the current position.
listens :: forall w a t b. Functor w => (t -> b) -> TracedT t w a -> TracedT t w (Tuple a b)
listens f (TracedT tr) = TracedT ((\g t -> Tuple (g t) (f t)) <$> tr)
-- | Apply a function to the current position.
censor :: forall w a t. Functor w => (t -> t) -> TracedT t w a -> TracedT t w a
censor f (TracedT tr) = TracedT ((f >>> _) <$> tr)
instance comonadTracedTracedT :: (Comonad w, Monoid t) => ComonadTraced t (TracedT t w) where
track t (TracedT tr) = extract tr t