|
1 | 1 | -- | This module defines functions for working with lenses. |
2 | 2 |
|
3 | | -module Data.Lens.Prism where |
4 | | - |
| 3 | +module Data.Lens.Prism |
| 4 | + ( prism, prism', review, nearly, only, clonePrism, withPrism, matching |
| 5 | + , is, isn't |
| 6 | + ) where |
| 7 | + |
5 | 8 | import Prelude |
6 | | - |
| 9 | + |
7 | 10 | import Data.Either |
| 11 | +import Data.Profunctor.Star |
| 12 | +import Data.Const |
| 13 | +import Data.Maybe |
| 14 | +import Data.Maybe.First |
8 | 15 | import Data.Lens.Types |
| 16 | +import Data.Lens.Internal.Tagged |
| 17 | +import Data.Lens.Internal.Market |
| 18 | +import Control.MonadPlus |
9 | 19 | import Data.Profunctor (dimap, rmap) |
10 | | -import Data.Profunctor.Choice (left) |
| 20 | +import Data.Profunctor.Choice |
11 | 21 |
|
12 | 22 | -- | Create a `Prism` from a constructor/pattern pair. |
13 | | -prism :: forall s t a b. (b -> t) -> (s -> Either a t) -> Prism s t a b |
14 | | -prism to fro pab = dimap fro (either id id) (left (rmap to pab)) |
| 23 | +prism :: forall s t a b. (b -> t) -> (s -> Either t a) -> Prism s t a b |
| 24 | +prism to fro pab = dimap fro (either id id) (right (rmap to pab)) |
| 25 | + |
| 26 | +prism' :: forall s a. (a -> s) -> (s -> Maybe a) -> PrismP s a |
| 27 | +prism' to fro = prism to (\s -> maybe (Left s) Right (fro s)) |
| 28 | + |
| 29 | +-- | Review a value through a `Prism`. |
| 30 | +review :: forall s t a b. Review s t a b -> b -> t |
| 31 | +review p = unTagged <<< p <<< Tagged |
| 32 | + |
| 33 | +nearly :: forall a. a -> (a -> Boolean) -> PrismP a Unit |
| 34 | +nearly x f = prism' (const x) (guard <<< f) |
| 35 | + |
| 36 | +only :: forall a. (Eq a) => a -> Prism a a Unit Unit |
| 37 | +only x = nearly x (== x) |
| 38 | + |
| 39 | +clonePrism :: forall s t a b. APrism s t a b -> Prism s t a b |
| 40 | +clonePrism l = withPrism l go where |
| 41 | + -- the type checker doesn't like `prism` for `go`... |
| 42 | + go to fro pab = dimap fro (either id id) (right (rmap to pab)) |
| 43 | + |
| 44 | +withPrism :: forall s t a b r. APrism s t a b -> ((b -> t) -> (s -> Either t a) -> r) -> r |
| 45 | +withPrism l f = case l (Market id Right) of |
| 46 | + Market g h -> f g h |
| 47 | + |
| 48 | +matching :: forall s t a b. APrism s t a b -> s -> Either t a |
| 49 | +matching l = withPrism l \_ f -> f |
| 50 | + |
| 51 | +is :: forall s t a b r. (BooleanAlgebra r) => APrism s t a b -> s -> r |
| 52 | +is l = either (const bottom) (const top) <<< matching l |
15 | 53 |
|
| 54 | +isn't :: forall s t a b r. (BooleanAlgebra r) => APrism s t a b -> s -> r |
| 55 | +isn't l = not <<< is l |
0 commit comments