packages feed

lens 2.9 → 5.3.6

raw patch · 140 files changed

Files

− .ghci
@@ -1,1 +0,0 @@-:set -isrc -idist/build/autogen -optP-include -optPdist/build/autogen/cabal_macros.h
.gitignore view
@@ -1,6 +1,21 @@-dist+dist/+dist-newstyle/+.hsenv/ docs wiki TAGS tags wip+.DS_Store+.*.swp+.*.swo+*.o+*.hi+*~+*#+cabal.project.local+.cabal-sandbox/+cabal.sandbox.config+.stack-work/+codex.tags+.ghc.environment.*
+ .hlint.yaml view
@@ -0,0 +1,22 @@+- arguments: [-XCPP, --cpp-ansi, --cpp-include=include]++- ignore: {name: Reduce duplication}+- ignore: {name: Redundant lambda}+- ignore: {name: Use >=>}+- ignore: {name: Use const}+- ignore: {name: Use module export list}+- ignore: {name: Use lambda-case}+- ignore: {name: Use tuple-section}+- ignore: {name: Use fewer imports}+- ignore: {name: "Use :"}+- ignore: {name: Use typeRep, within: [Control.Lens.Internal.Typeable, Control.Lens.Internal.Exception]}+- ignore: {name: Eta reduce, within: [Control.Lens.At, Control.Lens.Zoom, Control.Lens.Equality, Control.Lens.Traversal]} # Breaks code+- ignore: {name: Use id, within: [Control.Lens.Equality]}+- ignore: {name: Use camelCase, within: [Control.Lens.Internal.TH]}+- ignore: {name: Use list comprehension, within: [Control.Lens.Internal.FieldTH]}+- ignore: {name: Use fmap, within: [Control.Exception.Lens, Control.Lens.Internal.Zoom, Control.Lens.Zoom, Control.Lens.Indexed, Control.Lens.Fold, Control.Monad.Error.Lens,Control.Lens.Setter]} # Needed to support pre-AMP GHC-7.8+- ignore: {name: Use uncurry}+- ignore: {name: Fuse concatMap/<&>, within: [Control.Lens.Internal.FieldTH]}++- fixity: "infixr 9 ..."+- fixity: "infixl 1 &~"
− .travis.yml
@@ -1,18 +0,0 @@-language: haskell-before_install:-  # Uncomment the next 3 lines whenever hackage is down.-  #  - mkdir -p ~/.cabal-  #  - cp config ~/.cabal/config-  #  - cabal update--  # adding the hunit test suite causes us to have to reinstall regex-posix and regex-base-  - cabal install --only-dependencies --enable-tests --enable-benchmarks --force-reinstall-install:-  # we have to configure rather than install in order to get benchmarks-  - cabal configure --enable-tests --enable-benchmarks -fdump-splices-  - cabal build-script:-  - cabal test --show-details=always-  - cabal bench-notifications:-  irc: "irc.freenode.org#haskell-lens"
.vim.custom view
@@ -15,7 +15,7 @@ syntax on  " search for the tags file anywhere between here and /-set tags=TAGS;/+set tags=TAGS;/,codex.tags;/  " highlight tabs and trailing spaces set listchars=tab:‗‗,trail:‗
+ AUTHORS.markdown view
@@ -0,0 +1,49 @@+Lens started as a one man project by++* [Edward Kmett](mailto:ekmett@gmail.com) [@ekmett](https://github.com/ekmett)++But it has been greatly enriched by opening it up to community development.++Many people have contributed patches, documentation, wiki pages, bug reports, test cases and massive quantities of code to `lens` including (among others):++* [Shachaf Ben-Kiki](mailto:shachaf@gmail.com) [@shachaf](https://github.com/shachaf)+* Elliott Hird [@ehird](https://github.com/ehird)+* [Johan Kiviniemi](mailto:lens@johan.kiviniemi.name) [@ion1](https://github.com/ion1)+* [Bas Dirks](mailto:ik@basdirks.eu) [@basdirks](https://github.com/basdirks)+* [Eric Mertens](mailto:emertens@gmail.com) [@glguy](https://github.com/glguy)+* [Michael Sloan](mailto:mgsloan@gmail.com) [@mgsloan](https://github.com/mgsloan)+* [Alexander Altman](mailto:alexanderaltman@me.com) [@phtariensflame](https://github.com/phtariensflame)+* [Austin Seipp](mailto:mad.one@gmail.com) [@thoughtpolice](https://github.com/thoughtpolice)+* [Dag Odenhall](mailto:dag.odenhall@gmail.com) [@dag](https://github.com/dag)+* [Aristid Breitkreuz](mailto:aristidb+lens@gmail.com) [@aristidb](https://github.com/aristidb)+* [Simon Hengel](mailto:sol@typeful.net) [@sol](https://github.com/sol)+* [@startling](https://github.com/startling)+* [Mike Ledger](mailto:eleventynine@gmail.com) [@mikeplus64](https://github.com/mikeplus64)+* [Niklas Haas](mailto:niklas.haas@uni-ulm.de) [@nandykins](https://github.com/nandykins)+* [Adrian Keet](mailto:arkeet@gmail.com) [@arkeet](https://github.com/arkeet)+* [Matvey B. Aksenov](mailto:matvey.aksenov@gmail.com) [@supki](https://github.com/supki)+* [Eyal Lotem](mailto:eyal.lotem+github@gmail.com) [@Peaker](https://github.com/Peaker)+* [Oliver Charles](mailto:ollie@ocharles.org.uk) [@ocharles](https://github.com/ocharles)+* Liyang HU [@liyang](https://github.com/liyang)+* [Carter Schonwald](mailto:carter.schonwald@gmail.com) [@cartazio](https://github.com/cartazio)+* [Mark Wright](mailto:gienah@gentoo.org) [@markwright](https://github.com/markwright)+* [Nathan van Doorn](mailto:nvd1234@gmail.com) [@Taneb](https://github.com/Taneb)+* Ville Tirronen [@aleator](https://github.com/aleator)+* [Mikhail Vorozhtsov](mailto:mikhail.vorozhtsov@gmail.com) [@mvv](https://github.com/mvv)+* [Brent Yorgey](mailto:byorgey@gmail.com) [@byorgey](https://github.com/byorgey)+* [Dan Rosén](mailto:danr@chalmers.se) [@danr](https://github.com/danr)+* Yair Chuchem [@yairchu](https://github.com/yairchu)+* [Michael Thompson](mailto:what_is_it_to_do_anything@yahoo.com) [@michaelt](https://github.com/michaelt)+* [John Wiegley](mailto:johnw@newartisans.com) [@jwiegley](https://github.com/jwiegley)+* [Jonathan Fischoff](mailto:jfischoff@yahoo.com) [@jfischoff](https://github.com/jfischoff)+* [Bradford Larsen](mailto:brad.larsen@gmail.com) [@bradlarsen](https://github.com/bradlarsen)+* [Alex Mason](mailto:axman6@gmail.com) [@Axman6](https://github.com/Axman6)+* [Ryan Scott](mailto:ryan.gl.scott@gmail.com) [@RyanGlScott](https://github.com/RyanGlScott)++You can watch them carry on the quest for bragging rights in the [contributors graph](https://github.com/ekmett/lens/graphs/contributors).++Omission from this list is by no means an attempt to discount your contributions!++Thank you for all of your help!++-Edward Kmett
CHANGELOG.markdown view
@@ -1,54 +1,1208 @@-2.9-------* Added `<<%~`, `<<.~`, `<<%=` and `<<.=` for accessing the old values targeted by a `Lens` (or a summary of those targeted by a `Traversal`)-* Renamed `|>` to `%`, as `%~` is the lensed version of `%`, and moved it to `Control.Lens.Getter` along with a version `^%` with tighter-  precedence that can be interleaved with `^.`-* Upgraded to `doctest` 0.9, which lets us factor out common `$setup` for our doctests-* Renamed `merged` to `choosing`. Added a simpler `chosen` operation to mirror `both`.-* Added `Control.Lens.Projection`-* Renamed `traverseException` to `exception` and `traverseDynamic` to `dynamic`, upgrading them to use `Projection`.-* `makeClassy` now places each generated `Lens` or `Traversal` inside the class it constructs when possible.-  This makes it possible for users to just export `HasFoo(..)`, rather than have to enumerate each lens in-  the export list. It can only do that if it creates the class. If the `createClass` flag is disabled, then-  it will default to the old behavior.-* Added `performs` to `Control.Lens.Action` to mirror `views` in `Control.Lens.Getter`.--2.8-----* Restored compatibility with GHC 7.2. This required a major version bump due to making some MPTC-based default signatures conditional.--2.7.0.1---------* Added the missing `Control.Lens.Combinators` to exported-modules! Its absence was causing it not to be included on hackage.--2.7-----* Generalized the signature of `Getting`, `Acting` and `IndexedGetting` to help out with the common user code scenario of needing to read-  and then write to change types.-* Documentation cleanup and additional examples.-* Renamed `au` to `ala`, introducing further incompatibility with the `newtype` package, but reducing confusion.-* Removed need for `Data.Map.Lens` and `Data.IntMap.Lens` by adding `TraverseMin` and `TraverseMax` to `Control.Lens.IndexedTraversal`.-* Flipped fixity of `~:` and `<~:`-* Added `++~`, `++=`, `<++~` and `<++=` to Data.List.Lens in response to popular demand.-* Added `|>`, `<$!>` and `<$!` to `Control.Lens.Combinators`, which exports combinators that are often useful in lens-based code, but that-  don't strictly involve lenses.-* Added an HUnit-based test suite by @orenbenkiki--2.6.1-------* Fixed bugs in `Traversal` code-generation.--2.6-----* Added build option `-f-inlining` to facilitate building with the various TH 2.8 versions used by GHC 7.6 and HEAD.-* Added build option `-f-template-haskell` for testing without template haskell. (Users should be able to assume TH is enabled; use this only for testing!)-* Added support for generating a `Traversal` rather than a `Lens` when multiple fields map to the same name or some constructors are missing a field.-* Removed `_` from the lens names in `System.FilePath.Lens`.-* Added `iwhere`, `withIndices`, `withIndicesOf`, `indices` and `indicesOf` to ease work with indexed traversals-* Added `assign` as an alias for `(.=)` in `Control.Lens.Setter`.-* Added `~:`, `=:`, `<~:` and `<=:` to `Data.List.Lens`--2.5+5.3.6 [2026.01.10]+------------------+* Allow building with `template-haskell-2.24.*` (GHC 9.14).+* Add `_SpecialiseEP` to `Language.Haskell.TH.Lens` (when building with+  `template-haskell-2.24.*`/GHC 9.14 or later).++5.3.5 [2025.06.17]+------------------+* Replace `test-framework` with `tasty` in the test suite.++5.3.4 [2025.03.03]+------------------+* Reduce the arity of `foldr1Of`, `foldl1Of`, `foldrOf'`, `foldlOf'`,+  `foldr1Of'`, `foldl1Of'`, `foldrMOf`, and `foldlMOf` so that GHC is more+  eager to inline them. On a simple benchmark involving `sumOf` (defined in+  terms of `foldlOf'`), this improves performance by 8x.+* Add `Ixed`, `Cons`, `Each`, `AsEmpty`, `Reversing`, and `Rewrapped` instances+  for strict boxed vectors when building with `vector-0.13.2` or later.+* Add an `AsEmpty` instance for primitive `Vector`s.++5.3.3 [2024.12.28]+------------------+* Add `makeFieldsId`, which generates overloaded field accessors using the+  same names as the underlying fields. This is intended for use with the+  `NoFieldSelectors` and `DuplicateRecordFields` language extensions.++  Also add `classIdFields :: LensRules` and `classIdNamer :: FieldNamer`, both+  of which use the same naming rules as `makeFieldsId`.+* Update the `Prism`s in `Language.Haskell.TH.Lens` to reflect additions to+  `template-haskell-2.23.0.0`:+  * Add an `_OrP` `Prism` for the `Pat` data type.+  * Add `_ForallE`, `_ForallVisE`, and `_ConstrainedE` `Prism`s for the `Exp`+    data type.++5.3.2 [2024.05.12]+------------------+* Define the following lenses that perform an operation and result the old+  result:+  * `(<<<>:~)` (prepend to the front via `(<>)` and return the old result)+  * `(<<<|~)` (prepend to the front via `(<|)` and return the old result)+  * `(<<|>~)` (append to the back via `(|>)` and return the old result)++  Each of these also has a variant that end with `=` instead of `~` (e.g.,+  `(<<<>:=)`) for working in a `MonadState` setting.+* Re-export `(<>:~)`, `(<<>:~)`, `(<|~)`, `(<<|~)`, `(|>~)`, and `(<|>~)` (as+  well as their variants which end with `=` instead of `~`, and their variants+  which return the old result) from `Control.Lens.Operators`.++5.3.1 [2024.05.05]+------------------+* Add a `Magnify` instance for the CPS variant of `RWST` when building with+  `mtl-2.3` or later.++5.3 [2024.05.04]+----------------+* Allow building with GHC 9.10.+* Update the `Prism`s in `Language.Haskell.TH.Lens` to reflect additions to+  `template-haskell-2.22.0.0`:+  * The `_InfixD` `Prism` now focuses on `(Fixity, NamespaceSpecifier, Name)`+    when building with `template-haskell-2.22.0.0` or later.+  * Add `Prism`s for the newly introduced `NamespaceSpecifier` data type.+  * Add `_TypeP` and `_InvisP` `Prism`s for the `Pat` data type.+  * Add a `_TypeE` `Prism` for the `Exp` data type.+  * Add a `_SCCP` `Prism` for the `Pragma` data type.+* Add the following `Setter`s for prepending and appending elements:+  * `(<>:~)`: prepend an element to the front via `(<>)`.+  * `(<<>:~)`: prepend an element to the front via `(<>)` and return the result.+  * `(<|~)`: cons an element to the front via `(<|)`.+  * `(<<|~)`: cons an element to the front via `(<|)` and return the result.+  * `(|>~)`: snoc an element to the back via `(|>)`.+  * `(<|>~)`: snoc an element to the back via `(|>)` and return the result.++  Each of these also has a variant that end with `=` instead of `~` (e.g.,+  `(<>:=)`) for working in a `MonadState` setting.++5.2.3 [2023.08.24]+------------------+* Allow building with GHC 9.8.+* Add new `Prism`s to `Language.Haskell.TH.Lens` to reflect recent additions to+  `template-haskell`:+  * `_GetFieldE` and `_ProjectionE` `Prism`s for the `Exp` data type, whose+    corresponding data constructors were introduced in+    `template-haskell-2.18.*`.+  * `_TypedBracketE` and `_TypedSpliceE` `Prism`s for the `Exp` data type, whose+    corresponding data constructors were introduced in+    `template-haskell-2.21.*`.+  * `_BndrReq` and `_BndrInvis` `Prism`s for the `BndrVis` data type, which was+    added in `template-haskell-2.21.*`.+* Add a `generateRecordSyntax` option to `Control.Lens.TH`, which controls+  whether to generate lenses using record update syntax or not. By default, this+  option is disabled.+* Fix a bug in which the `declare*` Template Haskell functions would fail if a+  data type's field has a type that is defined in the same Template Haskell+  quotation.+* Add `altOf`, which collects targets into any `Alternative`.++5.2.2 [2023.03.18]+------------------+* Fix a bug in which calling `ix i` (where `i` is a negative number) on `Text`+  or `ByteString` would return the `Just` the first character instead of+  returning `Nothing`.++5.2.1 [2023.02.27]+------------------+* Allow building with GHC 9.6.+* Allow building with GHC backends where `HTYPE_SIG_ATOMIC_T` is not defined,+  such as the WASM backend.+* Support building with `th-abstraction-0.5.*`.+* Define `_TypeDataD` in `Language.Haskell.TH.Lens` when building with+  `template-haskell-2.20.0.0` (GHC 9.6) or later.++5.2 [2022.08.11]+----------------+* Allow building with GHC 9.4.+* The type of `universeOf` has changed:++  ```diff+  -universeOf :: Getting       [a]  a a -> a -> [a]+  +universeOf :: Getting (Endo [a]) a a -> a -> [a]+  ```++  In many cases, using `Endo [a]` over `[a]` improves performance. Most call+  sites to `universeOf` will not be affected by this change, although you may+  need to update your code if you define your own combinators in terms of+  `universeOf`.+* Allow `makeWrapped` to accept the names of data constructors. This way,+  `makeWrapped` can be used with data family instances, much like other+  functions in `Control.Lens.TH`.+* Define `_OpaqueP`, `_DefaultD`, `_LamCasesE`, `_PromotedInfixT`, and+  `_PromotedUInfixT` in `Language.Haskell.TH.Lens` when building with+  `template-haskell-2.19.0.0` (GHC 9.4) or later.++5.1.1 [2022.05.17]+------------------+* Add `Data.HashSet.Lens.hashMap`, an `Iso` between a `HashSet a` and a+  `HashMap a ()`.+* Allow building with `transformers-0.6.*` and `mtl-2.3.*`.++  Note that `lens` no longer defines `Zoom` instances for `ErrorT` or `ListT`+  when building with `mtl-2.3` or later. This is because `MonadState` is a+  superclass of `Zoom`, and the `MonadState` instances for `ErrorT` and `ListT`+  were removed in `mtl-2.3`. Be watchful of this if you build `lens` with+  `mtl-2.3` (or later) combined with an older version of `transformers`+  (pre-`0.6`) that defines `ErrorT` or `ListT`.++5.1 [2021.11.15]+----------------+* Allow building with GHC 9.2.+* Drop support for GHC 7.10 and older.+* The type of `_ConP` in `Language.Haskell.TH.Lens` is now+  `Prism' Pat (Name, [Type], [Pat])` instead of `Prism' Pat (Name, [Pat])`+  when building with `template-haskell-2.18` or later.+* Define `_CharTyLit` in `Language.Haskell.TH.Lens` when building with+  `template-haskell-2.18` or later.+* Add `Prefixed` and `Suffixed` classes to `Control.Lens.Prism`, which provide+  `prefixed` and `suffixed` prisms for prefixes and suffixes of sequence types.+  These classes generalize the `prefixed` and `suffixed` functions in+  `Data.List.Lens`, which were previously top-level functions. In addition to+  providing `Prefixed` and `Suffixed` instances for lists, instances for `Text`+  and `ByteString` types are also provided.++  At present, `Prefixed` and `Suffixed` are re-exported from `Data.List.Lens`+  for backwards compatibility. This may change in a future version of `lens`,+  however.+* Add a `traversal` function to `Control.Lens.Traversal`. This function, aside+  from acting as a `Traversal` counterpart to the `lens` and `prism` functions,+  provides documentation on how to define `Traversal`s.+* Add a `matching'` function to `Control.Lens.Prism`. `matching'` is like+  `matching`, but with a slightly more general type signature that allows it to+  work with combinations of `Lens`es, `Prism`s, and `Traversal`s.++5.0.1 [2021.02.24]+------------------+* Fix a bug in which `makeLenses` could produce ill kinded optics for+  poly-kinded datatypes in certain situations.++5 [2021.02.17]+--------------+* Support building with GHC 9.0.+* Remove the `Swapped` type class in favor of `Swap` from the `assoc` package.+* Remove the `Strict` type class in favor of `Strict` from the `strict` package.++  The `swapped`, `strict` and `lazy` isomorphisms are now defined using "new" type classes.++  Users which define own instances of old type classes are advised to+  define instances of the new ones.++  ```haskell+  import qualified Data.Bifunctor.Swap as Swap+  import qualified Control.Lens        as Lens++  instance Swap.Swap MyType where+    swap = ...++  #if !MIN_VERSION_lens(4,20,0)+  instance Lens.Swapped MyType where+    swapped = iso Swap.swap Swap.swap+  #endif+  ```+* The `FunctorWithIndex`, `FoldableWithIndex` and `TraversableWithIndex` type classes+  have been migrated to a new package,+  [`indexed-traversable`](https://hackage.haskell.org/package/indexed-traversable).++  The `imapped`, `ifolded` and `itraversed` methods are now top-level functions.+  If you are not defining these methods in your instances,+  you don't need to change your definitions.++  Beware: the `optics-core` package (versions <0.4) defines similar classes,+  and will also migrate to use `indexed-traversable` classes. Therefore, you+  might get duplicate instance errors if your package defines both.++  If you define your own `FunctorWithIndex` etc. instances,+  we recommend that you depend directly on the `indexed-traversable` package.+  If you want to continue support `lens-4` users, you may write++  ```haskell+  -- from indexed-traversable+  import Data.Functor.WithIndex++  -- from lens+  import qualified Control.Lens as L++  -- your (indexed) container+  data MySeq a = ...++  -- indexed-traversable instance+  instance FunctorWithIndex     Int MySeq where imap = ...+  instance FoldableWithIndex    Int MySeq where ifoldMap = ...+  instance TraversableWithIndex Int MySeq where itraverse = ...++  -- lens <5 instance, note the !+  #if !MIN_VERSION_lens(5,0,0)+  instance L.FunctorWithIndex     Int MySeq where imap = imap+  instance L.FoldableWithIndex    Int MySeq where ifoldMap = ifoldMap+  instance L.TraversableWithIndex Int MySeq where itraverse = itraverse+  #endif+  ```++  In other words, always provide `indexed-traversable` instances.+  If your package depends on `lens` and allows `lens-4`,+  you should additionally provide instances for `lens-4` type classes+  that can reuse the `indexed-traversable` instances.++* Make the functions in `Control.Lens.TH` work more robustly with poly-kinded+  data types. This can cause a breaking change under certain situations:+  * TH-generated optics for poly-kinded data types are now much more likely to+    mention kind variables in their definitions, which will require enabling+    the `PolyKinds` extension at use sites in order to typecheck.+  * Because TH-generated optics now quantify more kind variables than they did+    previously, this can affect the order of visible type applications.+* Generalize the types of `generic` and `generic1` to allow type-changing+  updates. If you wish to use the old, more restricted types of these+  functions, use `simple . generic` or `simple . generic1` instead.+* Add `Control.Lens.Profunctor` with conversion functions to and from+  profunctor optic representation.+* Add `Control.Lens.Review.reviewing`, which is like `review` but with a more+  polymorphic type.+* Mark `Control.Lens.Equality` as Trustworthy.+* The build-type has been changed from `Custom` to `Simple`.+  To achieve this, the `doctests` test suite has been removed in favor of using [`cabal-docspec`](https://github.com/phadej/cabal-extras/tree/master/cabal-docspec) to run the doctests.+* Use `alterF` in `At (HashMap k)` instance implementation.+* Use `alterF` in `At` and `Contains` instances for `Set`, `IntSet`, and+  `HashSet`.+* Avoid re-inserting keys already present in `ix` for `Set`, `IntSet`,+  and `HashSet`. For `Set` and `HashSet`, this changes the semantics+  slightly; if the user-supplied key is `==` to one already present in+  the set, then the latter will not be replaced in the result.+* Consume `()` values lazily in `Control.Lens.At`.++4.19.2 [2020.04.15]+-------------------+* Remove the test suite's dependency on `test-framework-th`.++4.19.1 [2020.02.13]+-------------------+* Fix a bug introduced in 4.19 where using `_TupE` to `preview` a value would+  always fail.++4.19 [2020.02.03]+-----------------+* Support building with GHC 8.10.+* The types of `_TupE` and `_UnboxedTupE` are now `Prism' Exp [Maybe Exp]`+  when built against `template-haskell-2.16` or later to reflect the new+  types of `TupE` and `UnboxedTupE`.+* Add `_ForallVisT` and `_BytesPrimL` prisms when building against+  `template-haskell-2.16` or later.+* Make `<>~` and `<>=` and their `<op` and `<<op` state variants require only+  `Semigroup`, not `Monoid`.+* Add `{Functor,Foldable,Traversable}WithIndex` instances for+  `Control.Applicative.Const` and `Data.Functor.Constant.Constant`.++4.18.1 [2019.09.13]+-------------------+* Remove the use of `cpp-options: -traditional`. This should be unnecessary+  on all versions of GHC that `lens` supports, as modern GHCs already use+  `-traditional` internally during preprocessing. More critically, the use+  of `cpp-options: -traditional` breaks profiling builds on GHC 8.8+  (see https://gitlab.haskell.org/ghc/ghc/issues/17185).++4.18 [2019.09.06]+-----------------+* Support building with GHC 8.8.+* Add `xplat` and `xplatf`.+* Flip `auf` to take the `Iso` in the same direction as `au`.+  Use the new `xplatf` or just call `coerce` for the old form.+* Weaken `holeInOne`'s `Category p` constraint to `Comonad (Corep p)`.+* Generalize the type of `GHC.Generics.Lens.generic1` from+  `Iso' (f a) (Rep1 f a)` to `Iso (f a) (f b) (Rep1 f a) (Rep1 f b)`.+* `makeClassyPrisms` now supports generating prisms for data types that share+  a name with one of its constructors. In such a scenario, the name of the+  classy prism for the data type will be prefixed with an extra `_` (for+  prefix names) or `.` (for infix names) to disambiguate it from the prism+  for the constructor.+* Several type classes in `Control.Exception.Lens` now have additional+  prisms corresponding to the data type that they focus on, in accordance+  with the new convention established in the bullet point above. For example,+  `AsNonTermination` now has an additional+  `__NonTermination :: Prism' t NonTermination` method, and the existing+  `_NonTermination :: Prism' t ()` method now has a default implementation in+  terms of `__NonTermination`.++  As a consequence of this change, you may need to update instances of these+  classes to implement the new prisms.+* Add additional bifunctor instances for `Swapped`.+* New lenses `head1` and `last1`, to access the first/last elements of+  a `Traversable1` container.+* Add `filteredBy`.+* Add `adjoin` to `Control.Lens.Unsound`.+* Add `Each (Either a a) (Either b b) a b` instance.+* Make `magnify` offer its getter argument the `Contravariant` and `Functor`+  instances it will require. This allows `magnify` to be used without+  knowing the concrete monad being magnified.+* Add `equality`, `equality'`, `withEquality`, `underEquality`, `overEquality`,+  `fromLeibniz`, `fromLeibniz'` and `cloneEquality` to `Control.Lens.Equality`.+* Add `withLens` to `Control.Lens.Lens`.+* Make `substEq` and `simply` in `Control.Lens.Equality`+  and `withIso` in `Control.Lens.Iso` levity polymorphic.++4.17.1 [2019.04.26]+-------------------+* Support `th-abstraction-0.3.0.0` or later.+* Only incur `semigroups` and `void` dependencies on old GHCs.+* Add `holes1Of`+* Add `locally` https://github.com/ekmett/lens/pull/829+* Add `ilocally` https://github.com/ekmett/lens/pull/836+* Add third `Prism` law.+* Add `gplate1`+* Add `Wrapped`/`Rewrapped` instances for `Data.Monoid.Ap`.++4.17 [2018.07.03]+-----------------+* Allow building with GHC 8.6.+* Make the instances for `Product` and `(:*:)` in `Control.Lens.Tuple`+  poly-kinded.+* Make the definitions in `GHC.Generics.Lens` poly-kinded.+* Make `(%%@~)`, `(%%@=)`, `(<%@=)`, and `(<<%@=)` consume an+  `Over (Indexed i)` instead of an `IndexedLensLike i` to improve type+  inference.+* Add an `AsEmpty` instance for `ZipList`.++4.16.1 [2018.03.23]+-------------------+* Re-export `(<&>)` from `Data.Functor` on `base-4.11` and later.+* Added `Cons` and `Snoc` instances for `Control.Applicative.ZipList`+* Fix a bug in which `makeFields` would generate equality constraints for+  field types involving data families, which are unnecessary.+* Improve the performance of `holesOf`.++4.16 [2018.01.28]+-----------------+* The `Semigroup` instances for `Traversed` and `Sequenced` are now more+  constrained (going from `Apply` to `Applicative` and `Monad`, respectively).+  In GHC 8.4, `Semigroup` is a superclass of `Monoid`, therefore we'd need to+  have `Apply` constraint in the `Monoid` instances. We opted to weaken our+  ability to use `Apply` than to lose compatibility with third-party packages+  that don't supply instances for `Apply`.++  In practice this changes the (specialised) type signature of `traverseOf_`+  ```diff++  - traverseOf_ :: Apply f       => Fold1 s a -> (a -> f r) -> s -> f ()+  + traverseOf_ :: Applicative f => Fold1 s a -> (a -> f r) -> s -> f ()+  ```+  and similarly for `forOf_` and `sequenceOf_`.++  As part of this change, new combinators `traverse1Of_`, `for1Of_` and+  `sequence1Of_` were added for `Apply`-only effects.++  Similar instance context changes were made for `Folding` and `Effect`,+  but these changes aren't publicly visible.++* Add `Control.Lens.Unsound`, which exports unsound functionality for forming+  products of lenses and sums of prisms.++* Add `Numeric.Natural.Lens`, which export convenient isomorphisms for+  natural numbers.++* Add `Strict` instances for strict and lazy `ST`.++* Adapt `Language.Haskell.TH.Lens` for `template-haskell-2.13` (bundled+  with GHC 8.4).++* Add `Semigroup` and `Monoid` instances for `Indexing`.++4.15.4+----+* `makeFields` and `declareFields` are now smarter with respect to type+  families. Because GHC does not allow mentioning type families in instance+  heads, the Template Haskell machinery works around this restriction by+  instead generating instances of the form:++  ```haskell+  type family Fam a+  data Rec a = Rec { _recFam :: Fam a }+  makeFields ''Rec++  ===>++  instance (b ~ Fam a) => HasFam (Rec a) b where ...+  ```++  This requires enabling the `UndecidableInstances` extension, so this trick is+  only employed when a field's type contains a type family application.+* `declareFields` now avoids creating duplicate field classes that are shared+  among multiple datatypes within the same invocation.+* The Template Haskell machinery will no longer generate optics for fields+  whose types mention existentially quantified type variables.+* Add `HasCallStack` constraints to partial operations+* Reexport `(.@~)` and `(.@=)` from `Control.Lens.Operators`+* Support `doctest-0.13`++4.15.3+----+* Generalized types of `transformMOf`, `transformOf`, `transformMOnOf`,+  `transformOnOf`, `rewriteMOf`, `rewriteOf`, `rewriteMOnOf` and `rewriteOnOf`.+* Depend on `th-abstraction` package for normalizing differences across+  `template-haskell` versions++4.15.2+----+* Build with GHC 8.2+* Expand tuple accessors to support up to 19-tuples+* Add more `Rewrapped` and `Wrapped` instances for data types from the `base`,+  `bifunctors`, `exceptions`, `free`, `profunctors`, and `semigroupoids`+  libraries+* Add a `Generic` default implementation for `Wrapped`+* Add `Wrapped` instances for data types introduced in `Foreign.C.Types` and+  `System.Posix.Types` in `base-4.10.0.0`+* Add prisms for recently introduced data types in `Control.Exception`+* Revamp `Setup.hs` to use `cabal-doctest`. This makes it build+  with `Cabal-1.25`, and makes the `doctest`s work with `cabal new-build` and+  sandboxes.+* Add `makeFieldsNoPrefix`, a variant of `makeFields` which gives the desired+  behavior in the presence of `DuplicateRecordFields`. Also add+  `classUnderscoreNoPrefixFields` and `classUnderscoreNoPrefixNamer`, the+  corresponding `LensRules` and `FieldNamer`, respectively.+* Add `toNonEmptyOf`, `first1Of`, `last1Of`, `minimum1Of`, and `maximum1Of`+  to `Control.Lens.Fold`+* Add `both1` to `Control.Lens.Traversal`+* Generalize the type of `levels` and `ilevels` in `Control.Lens.Level` to work+  on `Fold`s+* Generalize the type of `getting` in `Control.Lens.Getter` to work with any+  `Optical`+* Add `throwing_` to `Control.Monad.Error.Lens` and `Control.Exception.Lens`+* Fix the meta-data in the .cabal file to properly indicate that this project+  has a BSD2 license++4.15.1+----+* Restore the `generic` and `generic1` functions in `GHC.Generics.Lens`++4.15+----+* Remove `Generics.Deriving.Lens` module.+* Incorporate `URec`, which was introduced in `GHC.Generics` in `base-4.9`. For compatibility with older versions of `base`, `lens` now conditionally depends on `generic-deriving`+* Add `Rewrapped` instance for `ExceptT`+* Add `FunctorWithIndex`, `FoldableWithIndex`, and `TraversableWithIndex` instances for `Sum`, `Proxy`, `Tagged` and data types in `GHC.Generics`+* Remove unneeded context from `*WithIndex HashMap` instances+* Add `Data.Map.Lens.toMapOf`+* Add moral `Functor` constraint for `to` `ito` `ilike` `ilike` to allow the+  "indented" type signature using Getter with redundant warnings turned on.++4.14+----+* Remove `Cons` and `Snoc` instances for `NonEmpty`.++4.13.2.1+------+* Fixed `itraverse_` and `imapM_` returning bottom++4.13.2+------+* Restore default signature for `Control.Lens.At.at`+* Improve operations for `Data.Sequence.Seq`+* Fix `declarePrisms` behavior on GHC 8 using GADT record syntax++4.13.1+------+* Modified to enable the `doctests` to build with `stack`.+* Removed `.ghci`.+* Added `lookupOf`+* Support GHC 8+* Support `transformers` 0.5+* Support `kan-extensions` 5+* Support `comonad` 5+* Better support for `Closed` from `profunctors`.++4.13+----+* Pattern synonyms+* Moved `foldMapBy` and `foldBy` into `reflection` 2.1+* Added `traverseByOf`, `sequenceByOf`.+* Reexported `traverseBy` and `sequenceBy` from `reflection` 2.1.+* Modified the signatures of `alaf` and `auf` to work with a `Functor` rather than a `Profunctor` and rather drastically generalized them.+* Removed `Control.Lens.Internal.Getter.coerce` in favor of the upstream `phantom` combinator in `contravariant` 1.3++* Renamed `coerced` to `phantasm` to get it out of the way.+* Added `Wrapped` instance for `Down`++4.12.3+------+* Move `Review` and `AReview` to `Control.Lens.Type` fixing a bug in `makePrisms`+* Expose `HasTypes` class in `Language.Haskell.TH.Lens`+* Make types of `foldByOf` and `foldMapByOf` more specific to hide implementation details+* Add Prisms to `Language.Haskell.TH` for new constructors in `template-haskell-2.10`+* Generalize type of `_FunDep` to an `Iso`++4.12.2+------+* Incorporated a bug fix for `foldByOf` and `foldMapByOf` to actually let them work on folds.+* Added a `Plated` instance for `CofreeT`++4.12.1+------+* The `Simple` type alias is now poly-kinded. This lets you use `Simple Field1 s a` and the like in constraints.+* Added `HasTypes` to `Language.Haskell.TH.Lens`.+* Support for `vector-0.11.0` which changes `Stream` to `Bundle`++4.12+----+* `reflection 2` support.++4.11.2+------+* Give `cosmosOn` a more general type.++4.11.1+------+* Added `cosmos`, `cosmosOf`, `cosmosOn`, `cosmosOnOf` to `Control.Lens.Plated`.+* Added `icontains`, `iat`, `iix`.+* Made various documentation improvements.+* Added a `test-templates` flag.++4.11+----+* Proper `profunctors` 5.1 support. This extended the superclass constraints for `Conjoined`, so it resulted in a major version bump.++4.10+----+* Added `elemIndexOf`, `elemIndicesOf`, `findIndexOf`, and `findIndicesOf`.+* Fixed `Ixed` instance for `Tree`. It no longer drops nodes prior to the traversed node.+* `bifunctors` 5, `profunctors` 5 and `semigroupoids` 5 support.++4.9.1+-----+* Added `_Wrapped` support for `NonEmpty`.+* Added `_Wrapped` support for `Alt`.+* Fixed `Rewrapped` instance for `Last`.++4.9+-------+* `filepath` 1.4 support+* Removed `Control.Monad.Primitive.Lens` and shed the `primitive` dependency.+* Add missing `_WithIndex` instances from `keys` package+* Much more code is inferred `Safe` rather than `Trustworthy`.+* Documented the difference between `unsafeSingular` and `singular`.+* `folding` now produces an actual `Fold`.+* Cleaned up builds for GHC 7.10 to get rid of redundant import warnings.++4.8+---+* When built with `profunctors` 4.4 on GHC 7.8+ we no longer need to use `unsafeCoerce` at all!+  This drastically reduces the level of trust involved in the way we have optimized `lens`.+* Added `fusing`. This optimizes long `Lens` chains, by enfocing a form of `fmap` fusion based on the Yoneda lemma. This is particularly effective at making faster lenses the definition is recursive or complex enough that it cannot be inlined.+* Added `confusing`. This optimizes long `Traversal` chains. As with `fusing` it is best used when the definition for the `Traversal` chain in question is recursive or complex enough that it cannot be inlined, but the implementation is much more confusing.+* Remove deprecated stuff: `Control.Lens.Loupe`, `headOf`, `makeFieldsWith`,+  `strippingPrefix`, `strippingSuffix`+* Added `Cons` and `Snoc` instances for `NonEmpty`+* Removed `Data.List.Split.Lens` module+* Reimplemented `bytestring` traversals to avoid internal modules+* Added `gplate`, an implementation of `plate` for any type implementing `Generic`+* Strictness revisited+  * Add `generateLazyPatterns` configuration flag to `makeLenses` rules.+  * Make the default `makeLenses` behavior to generate STRICT optics+  * Add strict variants of `_1` .. `_9` named `_1'` .. `_9'`+* Generalized some combinators in `Data.Vector.Generic.Lens` and added `converted`++4.7+---+* Migrated `Control.Lens.Action` to `lens-action`.+* Added `Data.Vector.Generic.Lens.vectorIx` function for indexing vectors with only `Vector` constraint.+* Added `Field1` and `Field2` instances for `Data.Functor.Product.Product`.+* Removed the "typeclass synonym" `Gettable`.+* Added new flag to `makeLenses`, `generateUpdateableOptics`, which allows+  the generation of only `Getter`s and `Fold`s. This feature is intended+  to be used when the constructors are hidden behind validating, "smart"+  constructors.+* Fixed Template Haskell name generation when using GHC 7.10+* Fixed Template Haskell generation of classes methods where field types used+  existential quantification++4.6.0.1 [maintenance release]+-------+* Compatibility with `base` 4.8 [Edit: this turned out to not work for the final release of GHC 7.10]++4.6+---+* Reduced `Review` to two arguments, like `Getter`.+* Added `abbreviatedFields` to permit `makeFieldsWith` to be invoked with an argument that lets it act like it did pre-4.5 and accept arbitrary common prefixes.++4.5+---+* Provide access to the typename in `lensRules` naming function.+* `makeFields` camelcasing rules now properly support types with camelcasing. `MyType` with field `myTypeFieldA` generates `fieldA` now. Previously the prefix ignore capitalization and the field would need to be named `mytypeFieldA`.+* `makeClassy` works on types even when none of the fields would generate optics.+* Added `Monad`, `MonadReader`, `MonadPlus` and `Bind` instances for `ReifiedMonadicFold`+* Added missing fixity declarations on many operators.+* Migrated `Codec.Compression.Zlib.Lens` to `zlib-lens` package.++4.4.0.2+---+* `text` 1.2.0.0 support+* Remove the use of the TemplateHaskell extension from the library to enable lens to be used on stage1 cross-compilers++4.4.0.1+----+* Restore previous default of `makeFields` using the camel case field namer.++4.4+----+* Internals of Template Haskell code generation rewritten. makeLenses,+  makeClassy, and makeFields have been unified into the same generator.+* TH generated single constructor Lens use irrefutable pattern matching to+  enable construction starting with undefined.+* TH generated traverals unify their field arguments (type synonyms not+  currently expanded) enabling exotic traversals to be generated.+* Added instances for `Text` to `Data.Aeson.Lens`+* Reimplemented `makePrisms`, adding support for `makeClassyPrisms`, infix constructrs generate periods (.) prefixed prisms.+* Added `Choice` to `Review` so that `Prism` is a proper subtype of `Review`+* Migrated `Data.Aeson.Lens` to `lens-aeson` package.+* Fixed `GHC.Generics.Lens.tinplate` behavior on single-field data types and empty data types.++4.3.3+-----+* `semigroupoids` 4.2 support++4.3.2+-----+* `contravariant` 1.0 support++4.3.1+-----+* Added `bytewise` to `Data.Bits`++4.3+---+* Switched the "direction" of the `Iso` argument to `au` to match the order generated by `makePrisms` and `makeLenses`.+* Removed `makeIsos` in favor of `makePrisms` and `makeLenses`. Each of these functions will construct `Iso`s when appropriate.+* Removed `declareIsos` in favor of `declarePrisms` and `declareLenses`. Each of these functions will construct `Iso`s when appropriate.+* Added `matching` for type-changing matches with `Prism`s.+* Added `withPrism` for recovering the functions passed to `prism`.+* Added `negated`, the isomorphism for the `negate` function.++4.2+---+* Added `_Text` isomorphisms to make the proper use with `(#)` more obvious and fit newer convention.+* Added `Wrapped` instances for `Vector` types+* Resolved issue #439.  The various `Prism`s for string-like types in `Data.Aeson.Lens` are now law-abiding `Prism`s "up to quotient."+* Added `selfIndex`.+* Support `attoparsec` 0.12.++4.1.2+-----+* When used with `exceptions` 0.4, `throwingM` will permit use with a mere `MonadThrow`.++4.1.1+----+* Generalized the types of `mapping`, `bimapping`, `contramapping`, `dimapping`, `lmapping`, `rmapping` to support changing the `Functor`, `Bifunctor`, `Contravariant`, and `Profunctor` respectively.+* Compatibility with `free` 4.6++4.1+---+* Added `Plated` instances for various free monad variants.+* Compatibility with GHC HEAD (7.9+)++4.0.7+-----+* Removed dependency on `constraints`. It was used in a pre-release version of 4.0 but never made it into 4.0, but the dependency had remained around complicating builds for GHC 7.4.++4.0.6+-----+* `makeLenses` attempt to make the accessors it can under existential quantification.+* Added `(&~)`.+* _Experimental_ support for parallel builds on GHC 7.8 with `cabal install lens -fj`. Due to at last one known issue with GHC, it isn't recommended to use this option when rebuilding lens, as a race condition on at least one platform has been seen in the wild.+* Added `RoleAnnotations` for GHC 7.8.1. These rule out a few user-accessible bottoms that could be caused by creative abuse of the new `Coercible` machinery. However, there was no `unsafeCoerce` exposed.+* Removed some impossible cases that required unwritable instances from the example doctypes.++4.0.5+-----+* Added `bimapping` to `Control.Lens.Iso`+* Restored correct behavior of `makePrism` on types with a single constructor.+* `makeLenses` now generates `Getter`s and `Fold`s on universally quantified fields.++4.0.4+-----+* Made `declareFields` work again.++4.0.3+-----+* Fixed random segfaulting when using `foldMapBy`.++4.0.2+-----+* Properly bundled the modules needed for the properties test suite into the tarball for hackage.++4.0.1+-----+* Typo fixes+* Exporting `Rewrapping` from `Control.Lens.Wrapped`.+* Removed the dependency on `cpphs`.++4.0+----+* Added `nearly` to `Control.Lens.Prism`.+* Added `Control.Lens.Empty`, exporting `_Empty`.+* We now require `DefaultSignatures`.+* Added `failing` and `ifailing` to `Control.Lens.Traversal`.+* Changed the signature of `Data.List.Split.Lens.condensing` due to the addition of `DropBlankFields` to `Data.List.Split.CondensePolicy` in `split`.+* Simplified `Each`, `Ixed`, and `Contains`. They are no longer indexed. The previous design was actively getting in the way of user-defined instances.+* Replaced more of our home-grown types with standard ones. They had previously been defined to help make more intelligible error messages, but when we switched to using `(Contravariant f, Functor f)` instead of `(Gettable f)`, these ceased to really help. Now you can define even more `lens`-compatible types (e.g. `Getter` and `Fold`) without depending on `lens`.+  * Replaced the use of `Accessor` with `Const`.+  * Replaced the use of `Mutator` with `Identity`.+  * Replaced the use of `Reviewed` with `Tagged`.+* Removed the deprecated `Control.Lens.Simple` module.+* Repurposed `Control.Lens.Combinators` to re-export `Control.Lens` sans any operators; previous residents rehomed to `Control.Lens.Lens`.+* Added `Control.Lens.Operators` to export just the operators. Varying your import styles between these supports many qualified usage scenarios.+* Simplified `Cons` and `Snoc`. Now they must be a `Prism`.+* Simplified `Contains`. This necessitated losing many instancs of `Contains`, but makes it much easier and more consistent to use and instantiate.+* Simplified the various `AsFoo` types in `Control.Exception.Lens`+* Simplified the types in `System.IO.Error.Lens`.+* Merged `lens-aeson` into `lens`.+* We're exiling `Control.Lens.Zipper` to a separate package. This will let the design for it iterate faster and let us explore the trade-offs between the 3.8 style and the 3.9 style of zippers.+* Generalized `alongside`, `inside`, `both`.+* Switched to a new `Typeable` version of `reflection` for the harder combinators in `Control.Exception.Lens`. This enables us to comply with GHC 7.7's ban on hand-written `Typeable` instances.+* Added a `_Show` `Prism`.+* Added `Control.Lens.Extras` for the combinator names we don't have the gall to claim outright, but which are consistent with the rest.+* Renamed the constructors for `ReifiedLens`, etc. to just be the name of their base type.+* Added many many missing instances for `ReifiedFold` and `ReifiedGetter`. This permits things like `runFold ((,) <$> Fold (traverse._1) <*> Fold (traverse._2))` to be a `Fold`+  and `ReifiedFold` can be used as a `Monad`, `Profunctor`, etc.+* Many performance optimizations.+* Switched to `exceptions` from `MonadCatchIO-transformers`+* Added types for working with `RelevantFold` and `RelevantTraversal`. These are a `Fold` or `Traversal` that always has at least one target. Since `Apply` isn't a superclass of `Applicative`, you occasionally need to convert between them, but it lets you more readily work with less unsafety.+* Changed `unwrapping` and `wrapping` to have the same constructor-oriented order as a `Prism` and renamed them t `_Wrapping` and `_Unwrapping` respectively.+* Drastically changed the way `_Wrapping` and `_Unwrapping` are built to get much better inference.+* There are about 15,000 lines of patches over the last year, so I'm sure we missed a few big changes.++3.10.1 [maintenance release]+------+* Compatibility with `base` 4.7++3.10.0.1 [maintenance release]+--------+* Compatibility with `text` 1.0++3.10+----+* Switched to `bifunctors`, `comonad`, `profunctors`, and `semigroupoids` 4.0.++3.9.2+-----+* Generalized signatures for `throwing` and `throwingM`.++3.9.1+-----+* 'condensingPolicy' was updated to work with 'split' 0.2.2++3.9.0.3+-------+* Bumped dependency on `generic-deriving` again.++3.9.0.2+-------+* Bumped dependency on `generic-deriving` to enable building on GHC HEAD.++3.9.0.1+-------+* Updated the field guide image to link to imgur. Sadly the overview haddock and the haddocks are not generated in the same directory, so the haddock hook for copying the image only works locally.++3.9+-----+* Changed `Getting` to take 3 arguments instead of 5. If you need the old behavior for portability you can use+  `Overloaded (Accessor r) s t a b` instead of `Getting r s t a b` and it'll work consistently back through the last few releases.+* Added `involuted` to `Control.Lens.Iso`.+* Factored out a common `reversed` definition from all the various forms of it around the library and placed it in `Control.Lens.Iso`.+* Added `binary`, `octal`, `decimal` and `hex` to `Numeric.Lens`.+* Added `sans` to `Control.Lens.At`.+* Improved interoperability:+  * Reimplemented `Gettable` as an alias for `Contravariant` and `Functor` together to derive `Getter` and `Fold`. This means you can now+    implement a `Getter` or `Fold` with only a Haskell 98 dependency (`contravariant`).+  * Removed `Reviewable`. We now use `Bifunctor` and `Profunctor` together to derive `Review`. This means you can now implement a `Review`+    with Haskell 98 dependencies (`profunctors` and `bifunctors`).+  * These changes enables more types to be defined without incurring a dependency on the `lens` package.++3.8.7.0-3.8.7.3 [maintenance releases]+-----+* Fixes to dependencies and pragmas.++3.8.6 [maintenance release]+-----+* Fixed an issue with `DefaultSignatures` being used outside of the appropriate `#ifdef` that caused compilation issues on GHC 7.0.2.+* Generalized the signature of `prism'`+* Added `\_Void` and `only` to `Control.Lens.Prism` and `devoid` to `Control.Lens.Lens`.+* Added `\_Nothing` to `Control.Lens.Prism`.+* Added `devoid` and `united` to `Control.Lens.Lens`.++3.8.5+-----+* Fixed more sporadic issues in doctests, caused by carrying flags from `$setup` between modules.++3.8.4+-----+* Renamed `strippingPrefix` to `prefixed`, `strippingSuffix` to `suffixed`. Left the old names as deprecated aliases.+* Fixed issues with the test suite caused by `doctests` carrying flags from the `$setup` block between modules.+* Benchmarks now use `generic-deriving` rather than `ghc-prim` directly, like the rest of the package.+* Added `Generics.Deriving.Lens`, which is now simply re-exported from `GHC.Generics.Lens`.++3.8.3+-----+* Added `strippingSuffix` and `stripSuffix` to `Data.Data.Lens`+* Added `unpackedBytes` and `unpackedChars` to `Data.ByteString.*.Lens`+* Added `unpacked` to `Data.Text.*.Lens`+* Added `(#)` as an infix form of `review` to ease using a `Prism` like a smart constructor in `Control.Lens.Review`.++3.8.2+-----+* Added a notion of `Handleable(handler, handler_)` to `Control.Exception.Lens` to facilitate constructing a `Handler` from an arbitrary `Fold` or `Prism`.+* Added a notion of `Handler` and `catches` to and `Control.Monad.Error.Lens` to mirror the `Control.Exception` and `Control.Monad.CatchIO` constructions.+* Added additional doctests and documentation.+* Improved error messages and support for types with arguments in `makeFields`.++3.8.1+-----+* Fixed a bug in `makeFields` in hierarchical modules.++3.8.0.2+-------+* Fixed an issue with running the `doctests` test suite when an older version of `semigroups` is installed.++3.8+---+* Overall:+  * Replaced each of the different `SimpleFoo` type aliases with `Foo'` throughout. The various `Simple` aliases can still be found in `Control.Lens.Simple` but are now deprecated.+  * Made sweeping changes to `Iso` and `Prism` and `Indexed` lenses internally. They are now based on `profunctors`. This affects how you use `indexed` in the resulting code and dramatically changed the meaning of `Overloaded`.+  * Generalized combinators to pass through indices unmodified wherever possible and added indexed variants to existing combinators. There are hundreds of these changes and they would swamp this list.+* `Control.Exception.Lens`+  * This module was created to add combinators and prisms that make it possible to work with GHC's extensible exceptions and monad transformer stacks more easily. There are knock-on changes in `Data.Dynamic.Lens`, `System.Exit.Lens`, and `System.IO.Error.Lens`.+* `Control.Lens.At`+  * Moved `At(at)` and `Contains(contains)` and factored out `Ixed(ix)`.+  * Deprecated `_at` and `resultAt`.+  * Removed various `ordinal` and `ix` combinators, which are subsumed by `Ixed(ix)`.+* `Control.Lens.Cons`+  * Consoldiated the various `_head`, `_tail`, `_init` and `_last` traversals that were scattered around the place into a pair of `Cons` and `Snoc` classes that provide `_Cons` and `_Snoc` prisms respectively, and combinators that build on top.+* `Control.Lens.Each`+  * Generalized the signature of `Each` to permit it to provide an `IndexedSetter` for `((->) e)`.+  * `Each` now uses an `Index` type family that is shared with `At`, `Ixed` and `Contains` to indicate these operations are related.+* `Control.Lens.Equality`+  * Added as a stronger form of `Iso` that can be used to safely cast.+  * Added the adverb `simply`, which can be used to simplify the types of most combinators in the library so they only take a simple lens, simple traversal, etc as their first argument instead. e.g. `simply view` forces `a ~ b`, `s ~ t` in the argument to `view`.+* `Control.Lens.Fold`+  * Added `foldr1Of'` and `foldl1Of'`.+  * Added `has` and `hasn't`.+* `Control.Lens.Indexed`+  * The various indexed combinators for each type were distributed to their respective modules. This module grew to encompass the remaining index-specifics.+  * Added `index` and `indices`, and removed `iwhere` and `iwhereOf`. Use `itraversed.indices even` and `bar.indices (>3)` instead.+* `Control.Lens.Internal`+  * This module was exploded into more manageable component modules.+* `Control.Lens.Iso`+  * `Strict(strict)` is now a `Simple Iso`.+  * Added `magma` and `imagma` which can be used to provide a 'debugging view' of a `Traversal`.+* `Control.Lens.Lens`+  * Restructuring split this module out from `Control.Lens.Type` and merged the contents `Control.Lens.IndexedLens`.+* `Control.Lens.Level`+  * This module was created to provide the breadth-first-search Traversals `levels` and `ilevels` which can be used to do (optionally depth-limited) breadth-first searches through arbitrary traversals reaching all leaves at finite depth in finite time. To use these in full accordance with the laws you should restrict yourself to commutative operations and finite containers, but they are useful even in the absence of these properties.+* `Control.Lens.Loupe`+  * In the interest of consistency, the `Loupe` alias has been deprecated in favor of `ALens`.+  * `Loupe` (and `ALens`) are now defined in terms of `Pretext` rather than `Context`. This permits them to be cloned at a reduced cost reducing the call for `ReifiedLens`.+* `Control.Lens.Operators`+  * Added this module for users who insist on qualified use, but want access to the operators. They can `import qualified Control.Lens as Lens` and `import Control.Lens.Operators` unqualified.+* `Control.Lens.Prism`+  * Added `prism'` to construct `SimplePrism`s.+* `Control.Lens.Reified`+  * Consolidated the various `ReifiedFoo` definitions into one module.+* `Control.Lens.Representable`+  * This module was removed. Its functionality may be split out into a separate package, but currently the `linear` package exports is own `Linear.Core` module to provide this functionality. It was taking lots of useful names for little functionality and didn't feel like the rest of the API.+* `Control.Lens.Review`+  * This module now factors the `review` functionality out of `Prism` and exposes `unto`, which is to `review` what `to` is to `view`.+* `Control.Lens.Setter`+  * Added `contramapped` and `argument` for mapping over inputs.+* `Control.Lens.Simple`+  * Removed the infix lens aliases and repurposed the module to house the now deprecated `SimpleFoo` type aliases, which were replaced universally with `Foo'`.+* `Control.Lens.TH`+  * `makeLenses` now generates `Lens'` and `Traversal'` where appropriate+  * Added `makePrisms` as a generalized `makeIso` that automatically generates a `Prism` for each constructor. `makePrisms` generates names with an `_Foo` convention. This was consolidated upon throughout the library to reduce namespace conflicts between prisms and lenses.+  * Added `makeFields`, which generates classes for each individual field in a data type.+  * Added `makeWrapped`, which automatically generates a `Wrapped` instance for a newtype.+* `Control.Lens.Type`+  * This module was repurposed to provide a single home for all the standard lens-like type aliases used when producing lenses. You still need to go to their respective modules to find the types for consuming lens-likes if you want to generate your own lens combinators+* `Control.Lens.Wrapped`+  * Added `wrapped'` and `unwrapped'` for scenarios where you need the help with type inference.+* `Control.Lens.Zipper`+  * Converted `Zipper` to walk a magma based on the original structure and to use indices from indexed traversals when restoring from tape. This also means that when zipping around within a balanced structure with ascending keys `moveTo` can operate in logarithmic time, but required changing the `Zipper` type to add the index type.+* `Data.Bits.Lens`+  * Added `byteAt`.+* `Data.ByteString.Lens`+  * `Data.ByteString.Lazy.Lens` now uses `Int64`-based indexing.+  * The `Traversal` for strict `ByteStrings` now construct a balanced tree up to a given grain size. This permits zipper based seeking to operate in logarithmic time and speeds up many traversals.+* `Numeric.Lens`+  * Created. `base` shows and reads integers at base-2 through base-36. `integral` can be used as a safe `fromInteger`/`toInteger`.++3.7.6 [maintenance release]+-----+* Fixed an issue with the `Complex` `Each` instance.++3.7.5 [maintenance release]+-----+* Fixed an errant `LANGUAGE` pragma++3.7.4 [maintenance release]+-----+* Backported the API for `ALens` and `ALens'` to support `snap` builds on old platforms.++3.7.3 [maintenance release]+-----+* Removed my intra-package dependency upper bounds for my own packages. In particular this enables us to work with `semigroups` 0.9.+* Switched to `transformers-compat` to avoid having unbuilding modules at the top of the documentation, and to ease 3rd party compatibility.+* Updated `Setup.lhs` to be compatible with Cabal 1.17++3.7.2 [maintenance release]+-----+* Bug fix for `Magnify`. It was missing functional dependencies to determine its `k` parameter from `m` or `n`.++3.7.1.2 [maintenance release]+-------+* Made the doctest test suite hide all but the exact versions of packages used to build this package to avoid problems with complicated user environments.+* Removed doctests based on `:t` as they are fragile and break across GHC versions.+* Fixed GHC 7.0.4 compatibility by guarding `DefaultSignatures` in `Control.Lens.Each`.++3.7.1.1 [maintenance release]+-------+* Removed tests that will (likely) fail in the presence of `hashable` 1.2++3.7.1+-----+* Added `preuse`, `preuses` to `Control.Lens.Fold`+* Added `Each(each)` to `Control.Lens.Each` for indexed traversal of potentially monomorphic containers.+* Added `indexing64` and `traversed64` for help with large containers.+* Generalized the type signature of `choosing`.+* Exported `unwrapped` from `Control.Lens.Wrapped`.+* Support for `hashable` 1.2+* Added `(??)` to `Control.Lens.Combinators`.++3.7.0.2+-------+* Fixed flagging for Safe Haskell.+* Fixed examples.+* Cleaned up the statement of the Prism laws.++3.7.0.1+-------+* Corrected bounds for hashable.+* Fixed compatibility with Haskell Platform 2011.4.0.0 -- you may have to install with --constraint="transformers = 0.2.2.0" to avoid getting new mtl and transformer versions installed.++[3.7](https://github.com/ekmett/lens/issues?milestone=11&page=1&state=closed)+-----+* Renamed `Projection` to `Prism`.+* Implemented a complete redesign of the way `Iso` and `Prism` are handled internally. Any `Iso` can now be used as a `Prism`.+* The `isos` combinator is no longer required. `iso` can now be used to construct an `Iso`.+* Changes to the signature of `from` and `under` were necessitated by the new design.+* Added `Control.Lens.Wrapped` providing a canonical isomorphism for newtypes.+* Repurposed `ala` to be closer to the original design in `newtype`, but added `au` and `alaf`.+* Added `_magnitude`, `_phase` and `_conjugate` to `Data.Complex.Lens`. Renamed other lenses for consistency: `_realPart`, `_imagPart`, `_polar`.+* Promoted `_left` and `_right` to prisms and moved them to `Control.Lens.Prism`.+* Generalized `view` and `views` to subsume the old functionality of `peruse` and `peruses`.+* Generalized `review` and `reviews` to both return a `MonadReader` and to work on a `Projection`.+* Added `view'`/`views'` and `use'`/`uses'` for `Simple` access to the environment/state.+* Added `set'`, a `Simple` version of `set`.+* Added `reuse` : `use` :: `review` : `view` and `reuses` : `uses` :: `reviews` : `views` for working a `Projection` from the current `MonadState`.+* Removed many isomorphisms for various newtypes. `_const`, `identity`, `_sum`, etc. Use `wrapping Const`, `wrapping Identity`, etc.+* Removed `Data.Monoid.Lens` now that its newtypes are instances of `Wrapped`, exporting the (`<>=`)-variants from `Control.Lens.*`.+* Renamed `via` to `cloneIso` for consistency.+* Moved `Indexed(..)` to `Control.Lens.Classes`.+* Renamed `index` to `indexed` to reduce conflicts with third-party libraries.+* Added `curried` and `uncurried` to `Control.Lens.Iso`.+* Added `Strict(strict)` for ad hoc overloading of conversions between strict and lazy variants of `ByteString` and `Text`.+* Bug fixes for `tugTo` and `jerkTo`.+* These no longer traverse in the wrong direction: `scanl1Of`, `scanr1Of`, `mapAccumLOf`, and `mapAccumROf`.+* Added `anon` to `Control.Lens.Iso`.+* Generalized the types of the `Control.Lens.Zipper` combinators to work with other MonadPlus instances.+* Added `withins` to `Control.Lens.Zipper` now that they can work better with [].+* Added `singular` and `unsafeSingular` to `Control.Lens.Traversal` to assert a `Traversal` is a `Lens`, a `Fold` is a `Getter` or a `MonadicFold` is an `Action`.+* Generalized `sequenceAOf_`'s type to match `sequenceA_`.+* Renamed `up`/`down`/`left`/`right` to `upward`/`downward`/`leftward`/`rightward` to reduce conflicts -- in particular with `Control.Arrow`.+* Readded `leftmost` and `rightmost` due to the verbosity of `farthest leftward`/`farthest rightward`.+* Added `preview`/`previews`/`firstOf` and deprecated `headOf`.+* Added `iview`/`iviews`/`iuse`/`iuses` to `Control.Lens.IndexedGetter`.+* We've generalized the type of Bazaar and provided generalized variants of `partsOf`, etc. that used it.++3.6.0.4 [maintenance release]+-------+* Added support for `test-framework` 0.8++3.6.0.3 [maintenance release]+-------+* Added support for `test-framework` 0.7++3.6.0.2 [maintenance release]+-------+* Added more explicit dependencies to the doctest suite.+* Disabled the 'expected failure' quickcheck tests that occasionally would fail with internal QuickCheck errors.++3.6.0.1 [maintenance release]+-------+* Added explicit dependency on containers and unordered-containers to the doctest suite++[3.6](https://github.com/ekmett/lens/issues?milestone=9&state=closed)+---+* Added `upon` (along with variants of it) to `Data.Data.Lens`, which can be used to generate a `Traversal` from a field accessor or any function that returns, unmodified,+  a single field that would be visited by `template`.+* Added some missing `examples/` files to the distribution.+* Renamed `Data.Bits.Lens.traverseBits` to `bits`.+* Removed `(^!?)`, which was an alias for `(^?!)`.+* Removed the need for `Trustworthy` by changing the implementation of `coerce` for `BazaarT`.+* Moved BazaarT to `Control.Lens.Internal`.+* Added `(<&>)` to `Control.Lens.Combinators`.+* `element` and `elementOf` are now indexed traversals rather than lenses and have moved to `Control.Lens.IndexedTraversal`. This both fixes their former partiality and lets you use chain indexed combinators with them.+* Added `elements` and `elementsOf` as indexed traversals for ordinal indexing into regular traversals that generalize `element` and `elementOf`.+* Renamed `Data.Complex.Lens.traverseComplex` to `complex`.+* Changed `Data.Complex.Lens.polarize` to a `Simple Iso`, due to the `RealFloat` constraint causing inference problems.+* Renamed `traverseLeft` and `traverseRight` to `_left` and `_right` respectively.+* Renamed `traverseSlice`, `traverseFrom`, and `traverseTo` in `Data.Sequence.Lens` to `sliced`, `slicedFrom`, and `slicedTo` respectively.+* Renamed `traverseAt` to `_at` in `Control.Lens.IndexedTraversal`.+* Renamed `traverseArray` to `_array` in `Data.Array.Lens`.+* Renamed and made the combinators in `Control.Lens.Zipper` more compositional to reduce third-party naming conflicts down to just `left` and `right`.+* Renamed `&=` and `|=` to `.&.=` and `.|.=` for consistency, mutatis mutandis their related operations.+* Added a `Plated` instances for `Language.Haskell.TH` types.+* Renamed `atIndex` and `atIndices` in `Data.Vector.Lens` and `Data.Vector.Generic.Lens` to `ordinal` and `ordinals` to match `Data.Sequence.Lens`++3.5.1+-----+* Improved SafeHaskell inference.++[3.5](https://github.com/ekmett/lens/issues?milestone=8&state=closed)+---+* Fixed a potential SafeHaskell issue where a user could use `undefined` to derive `unsafeCoerce`. You now have to import an explicitly+  Unsafe module and create an instance of `Trustworthy` for your type to cause this behavior, so if you do, it's on your head, not mine. :)+* Renamed `EvilBazaar` to `BazaarT`.+* Moved a lot of internals around. Most notably, `Gettable`, `Settable` and `Effective` have moved to `Control.Lens.Classes`.+* Exposed `partsOf'` and `unsafePartsOf'` in `Control.Lens.Traversal` to reduce reliance on `BazaarT` in `Control.Lens.Zipper`++[3.4](https://github.com/ekmett/lens/issues?milestone=7&state=closed)+---+* Renamed `(%)` to `(&)` and `(^%)` to `(^&)`. This avoids the conflict with `Data.Ratio`, which was our highest priority conflict with a third party library.+* Switched to a more liberal type for `ignored`+* Removed some "`isplitting`" bad combinators from `Control.Lens.IndexedFold`.+* Made `indexed`, `taking`, and `dropping` and `elementOf` lazier and capable of dealing with infinite traversals and infinite folds.+* Improved `Indexing` to support infinite traversals and folds.+* Removed some of the more redundant combinators from `Control.Lens.Plated`, which already had existing aliases in the rest of the traversal API.+* Moved `partsOf`, `holesOf`, and `elementOf` into `Control.Lens.Traversal`.+* Renamed `query` to `peruse` and `queries` to `peruses`. These are much less contentious names,+  both contain `use` in their name for analogy to `use` and `uses` and the word is about reading.+* Simpler `simple`.+* Added `enum` and `non` to `Control.Lens.Iso`.+* Added `(^?!)` to `Control.Lens.Fold` for unsafe access to the head of a `Fold`.+* Changed `_head`, `_tail`, `_init` and `_last` to traversals in `Data.List.Lens` and `Data.Sequence.Lens`.+* Eliminated `traverseHead`, `traverseTail`, `traverseInit` and `traverseLast`.+* `partsOf` and `unsafePartsOf` can now also be applied to a `Fold` yielding a `Getter` or to a `MonadicFold` yielding an `Action`.++3.3+---+* Redefined `simple` and moved it to `Control.Lens.Iso`. Instead of using `simple l` you can now compose `l.simple` or `simple.l` providing more nuanced control and a more compositional API.+* Moved the various `foo#` combinators used to emit cleaner core into an unexported module, `Control.Lens.Unsafe`. This removes `MagicHash` from the public API.+* Removed the `bazaar#` and `runBazaar#` coercions that caused issues on GHC HEAD.+* Changed the default definition of `plate` to `uniplate` from `ignored`.+* Added `Data.Vector.Lens` and instances for `Data.Vector`.+* Added support for the `split` package, which is now part of the Haskell platform.+* Removed redundant `Data.List.traverseList`. Use `itraversed` or `traverse` instead.+* Moved `(:<->)` to `Control.Lens.Simple`.+* Fixed a bug in `Control.Lens.TH` that was causing `makeIso` not to work.+* Added `lifted` to `Control.Lens.Setter` for mapping over monads.+* Added `beside` to `Control.Lens.Traversal`.+* Removed the operators from `Data.List.Lens`, they broke the overall pattern of the rest of the API, and were terrible clutter.+* Fixed a bug that caused `resultAt` to give wrong answers most of the time.+* Changed `resultAt` to an `IndexedLens` and moved it to `Control.Lens.IndexedLens`+* Changed `ignored` to an `IndexedTraversal` and moved it to `Control.Lens.IndexedTraversal`+* We've relinquished the name `value`.++3.2+---+* Made `elementOf` lazier and moved it from `Control.Lens.Traversal` to `Control.Lens.Plated`.+* Made `holesOf` and `partsOf` lazier to deal with infinite structures.+* Resolved issue #75. We now generate nicer core for most `Setter` and `Fold` operations, and some others.+* Made lenses for field access like `_1`, `_2`, etc. lazier.+* Added `Control.Lens.Loupe`, which provides a limited form of `Lens` that can be read from and written to and which can compose+  with other lenses, but can also be returned in a list or as a monadic result, but cannot be used directly for most combinators+  without cloning it first. It is easier to compose than a `ReifiedLens`, but slightly slower.+* Moved (`:=>`) and (`:->`) into `Control.Lens.Simple`, which is not exported by `Control.Lens` by default to reduce name conflicts with third party libraries.++3.1+---+* Simplified the type of `filtered`, so that it can be composed with other folds rather than be parameterized on one. Included the caveat that the new `filtered` is still not a legal `Traversal`, despite seeming to compose like one.+* Renamed `ifiltered` to `ifiltering`, and while it still must take an indexed lens-like as an argument, I included a similar caveat about the result not being a legal `IndexedLens` when given an `IndexedLens`. The function was renamed because its signature no longer lined up with the new `filtered` and the gerundive '-ing' suffix has come to indicate an operator that transformers another lens/traversal/etc. into a new one.+* Added `taking` and `dropping` to `Control.Lens.Traversal`.++3.0.6+-----+* Alpha-renamed all combinators to a new scheme. Instead of `Foo a b c d`, they now follow `Foo s t a b`. This means that you don't need to alpha rename everything in your head to work through the examples, simplifies exposition, and uses s and t for common state monad parameters. Thanks go to Shachaf Ben-Kiki for the grunt work of slogging through hundreds of definitions by hand and with regular expressions!+* Restored lenses to `Trustworthy` status so they can be used with Safe Haskell once more.++3.0.5+-----+* Fixed a bug in `rights1` and `lefts1` in `Control.Lens.Zipper` which would cause them to loop forever when given a 0 offset.++3.0.4+-----+* Added `?~`, `<?~`, `?=` and `<?=` to `Control.Lens.Setter` for setting the target(s) of a Lens to `Just` a value. They are particularly useful when combined with `at`.++3.0.3+-----+* Refined the behavior of `substType` in `Control.Lens.TH` to match the behavior of `typeVarsEx` when moving under binders.+++3.0.2+-----+* Added `generateSignatures` option to `Control.Lens.TH` to allow the end user to disable the generation of type signatures for the+  template-haskell generated lenses. This lets the user supply hand-written haddocks and more restricted signatures.++3.0.1+-----+* Added `Control.Lens.Type.simple`.++[3.0](https://github.com/ekmett/lens/issues?milestone=6&state=closed)+---+* Added `Control.Lens.Zipper`.+* Added `<<~`, a version of `<~` that supports chaining assignment.+* Added `:->`, `:=>`, and `:<->` as type operator aliases for `Simple Lens`, `Simple Traversal`, and `Simple Iso`  respectively.++[2.9](https://github.com/ekmett/lens/issues?milestone=5&state=closed)+---+* Added `<<%~`, `<<.~`, `<<%=` and `<<.=` for accessing the old values targeted by a `Lens` (or a summary of those targeted by a `Traversal`)+* Renamed `|>` to `%`, as `%~` is the lensed version of `%`, and moved it to `Control.Lens.Getter` along with a version `^%` with tighter+  precedence that can be interleaved with `^.`+* Upgraded to `doctest` 0.9, which lets us factor out common `$setup` for our doctests+* Renamed `merged` to `choosing`. Added a simpler `chosen` operation to mirror `both`.+* Added `Control.Lens.Projection`+* Renamed `traverseException` to `exception` and `traverseDynamic` to `dynamic`, upgrading them to use `Projection`.+* `makeClassy` now places each generated `Lens` or `Traversal` inside the class it constructs when possible.+  This makes it possible for users to just export `HasFoo(..)`, rather than have to enumerate each lens in+  the export list. It can only do that if it creates the class. If the `createClass` flag is disabled, then+  it will default to the old behavior.+* Added `performs` to `Control.Lens.Action` to mirror `views` in `Control.Lens.Getter`.++[2.8](https://github.com/ekmett/lens/issues?milestone=4&state=closed)+---+* Restored compatibility with GHC 7.2. This required a major version bump due to making some MPTC-based default signatures conditional.++2.7.0.1+-------+* Added the missing `Control.Lens.Combinators` to exported-modules! Its absence was causing it not to be included on hackage.++[2.7](https://github.com/ekmett/lens/issues?milestone=3&state=closed)+---+* Generalized the signature of `Getting`, `Acting` and `IndexedGetting` to help out with the common user code scenario of needing to read+  and then write to change types.+* Documentation cleanup and additional examples.+* Renamed `au` to `ala`, introducing further incompatibility with the `newtype` package, but reducing confusion.+* Removed need for `Data.Map.Lens` and `Data.IntMap.Lens` by adding `TraverseMin` and `TraverseMax` to `Control.Lens.IndexedTraversal`.+* Flipped fixity of `~:` and `<~:`+* Added `++~`, `++=`, `<++~` and `<++=` to Data.List.Lens in response to popular demand.+* Added `|>`, `<$!>` and `<$!` to `Control.Lens.Combinators`, which exports combinators that are often useful in lens-based code, but that+  don't strictly involve lenses.+* Added an HUnit-based test suite by @orenbenkiki++2.6.1+-----+* Fixed bugs in `Traversal` code-generation.++[2.6](https://github.com/ekmett/lens/issues?milestone=2&state=closed)+---+* Added build option `-f-inlining` to facilitate building with the various TH 2.8 versions used by GHC 7.6 and HEAD.+* Added build option `-f-template-haskell` for testing without template haskell. (Users should be able to assume TH is enabled; use this only for testing!)+* Added support for generating a `Traversal` rather than a `Lens` when multiple fields map to the same name or some constructors are missing a field.+* Removed `_` from the lens names in `System.FilePath.Lens`.+* Added `iwhere`, `withIndices`, `withIndicesOf`, `indices` and `indicesOf` to ease work with indexed traversals+* Added `assign` as an alias for `(.=)` in `Control.Lens.Setter`.+* Added `~:`, `=:`, `<~:` and `<=:` to `Data.List.Lens`++[2.5](https://github.com/ekmett/lens/issues?milestone=1&state=closed) --- * Added `Control.Lens.Plated`, a port of Neil Mitchell's `uniplate` that can be used on any `Traversal`. * Added `Data.Data.Lens` with smart traversals that know how to avoid traversing parts of a structure that can't contain a given type.
LICENSE view
@@ -1,4 +1,4 @@-Copyright 2012 Edward Kmett+Copyright 2012-2016 Edward Kmett  All rights reserved. @@ -12,10 +12,6 @@ 2. Redistributions in binary form must reproduce the above copyright    notice, this list of conditions and the following disclaimer in the    documentation and/or other materials provided with the distribution.--3. Neither the name of the author nor the names of his contributors-   may be used to endorse or promote products derived from this software-   without specific prior written permission.  THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
README.markdown view
@@ -1,19 +1,22 @@ Lens: Lenses, Folds, and Traversals ================================== -[![Build Status](https://secure.travis-ci.org/ekmett/lens.png?branch=master)](http://travis-ci.org/ekmett/lens)+[![Hackage](https://img.shields.io/hackage/v/lens.svg)](https://hackage.haskell.org/package/lens) [![Build Status](https://github.com/ekmett/lens/workflows/Haskell-CI/badge.svg)](https://github.com/ekmett/lens/actions?query=workflow%3AHaskell-CI) [![Hackage Deps](https://img.shields.io/hackage-deps/v/lens.svg)](http://packdeps.haskellers.com/reverse/lens)  This package provides families of [lenses](https://github.com/ekmett/lens/blob/master/src/Control/Lens/Type.hs), [isomorphisms](https://github.com/ekmett/lens/blob/master/src/Control/Lens/Iso.hs), [folds](https://github.com/ekmett/lens/blob/master/src/Control/Lens/Fold.hs), [traversals](https://github.com/ekmett/lens/blob/master/src/Control/Lens/Traversal.hs), [getters](https://github.com/ekmett/lens/blob/master/src/Control/Lens/Getter.hs) and [setters](https://github.com/ekmett/lens/blob/master/src/Control/Lens/Setter.hs). -An overview of the [derivation](https://github.com/ekmett/lens/wiki/Derivation) of these types can be found on the [Lens Wiki](https://github.com/ekmett/lens/wiki) along with a brief [Overview](https://github.com/ekmett/lens/wiki/Overview).+If you are looking for where to get started, [a crash course video](http://youtu.be/cefnmjtAolY?hd=1) on how `lens` was constructed and how to use the basics is available on youtube. It is best watched in high definition to see the slides, but the [slides](http://comonad.com/haskell/Lenses-Folds-and-Traversals-NYC.pdf) are also available if you want to use them to follow along. -Documentation is available through [github](http://ekmett.github.com/lens/frames.html) or [hackage](http://hackage.haskell.org/package/lens).+The [FAQ](https://github.com/ekmett/lens/wiki/FAQ), which provides links to a large number of different resources for learning about lenses and an overview of the [derivation](https://github.com/ekmett/lens/wiki/Derivation) of these types can be found on the [Lens Wiki](https://github.com/ekmett/lens/wiki) along with a brief [overview](https://github.com/ekmett/lens/wiki/Overview) and some [examples](https://github.com/ekmett/lens/wiki/Examples). +Documentation is available through [github](https://ekmett.github.io/lens/frames.html) (for HEAD) or [hackage](http://hackage.haskell.org/package/lens) for the current and preceding releases.+ Field Guide ----------- -[![Lens Hierarchy](https://s3.amazonaws.com/creately-published/h5nyo9ne1)](https://creately.com/diagram/h5nyo9ne1/LBbRz63yg4yQsTXGLtub1bQU4%3D)+[![Lens Hierarchy](https://raw.githubusercontent.com/wiki/ekmett/lens/images/Hierarchy.png)](https://creately.com/diagram/h5nyo9ne1/QZ9UBOtw4AJWtmAKYK3wT8Mm1HM%3D) + Examples -------- @@ -47,11 +50,11 @@ ```  ```haskell-ghci> set (_2._1) 42 ("hello","world")+ghci> set (_2._1) 42 ("hello",("world","!!!")) ("hello",(42,"!!!")) ``` -You can make a `Getter` out of a pure functions with `to`.+You can make a `Getter` out of a pure function with `to`.  ```haskell ghci> "hello"^.to length@@ -69,10 +72,10 @@  ```haskell ghci> _1 .~ "hello" $ ((),"world")-("hello","world)+("hello","world") ``` -Conversely `view`, can be used as an infix alias for `(^.)`.+Conversely `view`, can be used as a prefix alias for `(^.)`.  ```haskell ghci> view _2 (10,20)@@ -86,8 +89,6 @@ You can let the library automatically derive lenses for fields of your data type  ```haskell-import Control.Lens- data Foo a = Foo { _bar :: Int, _baz :: Int, _quux :: a } makeLenses ''Foo ```@@ -95,13 +96,13 @@ This will automatically generate the following lenses:  ```haskell-bar, baz :: Simple Lens (Foo a) Int+bar, baz :: Lens' (Foo a) Int quux :: Lens (Foo a) (Foo b) a b ```  A `Lens` takes 4 parameters because it can change the types of the whole when you change the type of the part. -Often you won't need this flexibility, a `Simple Lens` takes 2 parameters, and can be used directly as a `Lens`.+Often you won't need this flexibility, a `Lens'` takes 2 parameters, and can be used directly as a `Lens`.  You can also write to setters that target multiple parts of a structure, or their composition with other lenses or setters. The canonical example of a setter is 'mapped':@@ -192,231 +193,49 @@ 5 ``` -You can automatically derive isomorphisms for your own newtypes with `makeIso`. e.g.+You can automatically derive isomorphisms for your own newtypes with `makePrisms`. e.g.  ```haskell newtype Neither a b = Neither { _nor :: Either a b } deriving (Show)-makeIso ''Neither+makePrisms ''Neither ```  will automatically derive  ```haskell-neither :: Iso (Neither a b) (Neither c d) (Either a b) (Either c d)-nor :: Iso (Either a b) (Either c d) (Neither a b) (Neither c d)+_Neither :: Iso (Neither a b) (Neither c d) (Either a b) (Either c d) ```  such that  ```haskell-from neither = nor-from nor = neither-neither.nor = id-nor.neither = id+_Neither.from _Neither = id+from _Neither._Neither = id ``` -There is also a fully operational, but simple game of [Pong](https://github.com/ekmett/lens/blob/master/examples/Pong.hs) in the [examples/](https://github.com/ekmett/lens/blob/master/examples/) folder.+Alternatively, you can use `makeLenses` to automatically derive isomorphisms for your own newtypes. e.g.. -There are also a couple of hundred examples distributed throughout the haddock documentation.+```hs+makeLenses ''Neither+``` -Operators-=========+will automatically derive -(See [`wiki/Operators`](https://github.com/ekmett/lens/wiki/Operators))+```hs+nor :: Iso (Either a b) (Either c d) (Neither a b) (Neither c d)+``` -<table>-<thead>-<tr>-  <th>Combinator(s)</th>-  <th>w/ Result</th>-  <th>Stateful</th>-  <th>w/ Result</th>-  <th>Notes</th>-</tr>-</thead>-<tbody>-<tr><th colspan=5><a href="http://ekmett.github.com/lens/Control-Lens.html">Control.Lens</a></th></tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Getter.html#v:view"><code>view</code></a>,<a href="http://ekmett.github.com/lens/Control-Lens-Getter.html#v:views"><code>views</code></a>,<a href="http://ekmett.github.com/lens/Control-Lens-Getter.html#v:-94-."><code>^.</code></a></td>-  <td/>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Getter.html#v:use"><code>use</code></a>,<a href="http://ekmett.github.com/lens/Control-Lens-Getter.html#v:uses"><code>uses</code></a></td>-  <td/>-  <td>View target(s). <a href="http://ekmett.github.com/lens/Control-Lens-Getter.html#v:query"><code>query</code></a> works like <a href="http://ekmett.github.com/lens/Control-Lens-Getter.html#v:use"><code>use</code></a> over a <code>MonadReader</code></td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:set"><code>set</code></a>, <a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:.-126-"><code>.~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-60-.-126-"><code>&lt;.~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:.-61-"><code>.=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:assign"><code>assign</code></a>,<a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-60-.-61-"><code>&lt;.=</code></a></td>-  <td>Replace target(s). <a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--60-.-126-"><code>&lt;&lt;.~</code> and-      <a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--60-.-61-"><code>&lt;&lt;.=</code></a>-      return the old value</td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:over"><code>over</code></a>,<a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:mapOf"><code>mapOf</code></a>,<a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-37--126-"><code>%~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--37--126-"><code>&lt;%~</code></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-37--61-"><code>%=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--37--61-"><code>&lt;%=</code></td>-  <td>Update target(s). <a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--60--37--126-"><code>&lt;&lt;%~</code> and-      <a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--60--37--61-"><code>&lt;&lt;%=</code></a>-      return the old value</td>-</tr>-<tr>-  <td><code>id</code>,<a href="http://ekmett.github.com/lens/Control-Lens-Traversal.html#v:traverseOf"><code>traverseOf</code></a>,<a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-37--37--126-"><code>%%~</code></a></td>-  <td/>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-37--37--61-"><code>%%=</code></a></td>-  <td/>-  <td>Update target(s) with an <code>Applicative</code> or auxillary result</td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-43--126-"><code>+~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--43--126-"><code>&lt;+~</code></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-43--61-"><code>+=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--43--61-"><code>&lt;+=</code></td>-  <td>Add to target(s)</td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-45--126-"><code>-~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--45--126-"><code>&lt;-~</code></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-45--61-"><code>-=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--45--61-"><code>&lt;-=</code></td>-  <td>Subtract from target(s)</td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-42--126-"><code>*~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--42--126-"><code>&lt;*~</code></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-42--61-"><code>*=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--42--61-"><code>&lt;*=</code></td>-  <td>Multiply target(s)</td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-47--47--126-"><code>//~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--47--47--126-"><code>&lt;//~</code></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-47--47--61-"><code>//=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--47--47--61-"><code>&lt;//=</code></td>-  <td>Divide target(s)</td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-94--126-"><code>^~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--94--126-"><code>&lt;^~</code></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-94--61-"><code>^=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--94--61-"><code>&lt;^=</code></td>-  <td>Raise target(s) to a non-negative <code>Integral</code> power</td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-94--94--126-"><code>^^~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--94--94--126-"><code>&lt;^^~</code></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-94--94--61-"><code>^^=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--94--94--61-"><code>&lt;^^=</code></td>-  <td>Raise target(s) to an <code>Integral</code> power</td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-42--42--126-"><code>**~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--42--42--126-"><code>&lt;**~</code></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-42--42--61-"><code>**=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--42--42--61-"><code>&lt;**=</code></td>-  <td>Raise target(s) to an arbitrary power</td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-124--124--126-"><code>||~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--124--124--126-"><code>&lt;||~</code></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-124--124--61-"><code>||=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--124--124--61-"><code>&lt;||=</code></td>-  <td>Logically or target(s)</td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-38--38--126-"><code>&amp;&amp;~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--38--38--126-"><code>&lt;&amp;&amp;~</code></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Setter.html#v:-38--38--61-"><code>&amp;&amp;=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Type.html#v:-60--38--38--61-"><code>&lt;&amp;&amp;=</code></td>-  <td>Logically and target(s)</td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Fold.html#v:headOf"><code>headOf</code>,<a href="http://ekmett.github.com/lens/Control-Lens-Fold.html#v:-94--63-"><code>^?</code></a></td>-  <td/><td/><td/>-  <td>Return <code>Just</code> the first target or <code>Nothing</code></td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Fold.html#v:toListOf"><code>toListOf</code>,<a href="http://ekmett.github.com/lens/Control-Lens-Fold.html#v:-94-.."><code>^..</code></a></td>-  <td/><td/><td/>-  <td>Return a list of the target(s)</td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Action.html#v:perform"><code>perform</code></a>,<a href="http://ekmett.github.com/lens/Control-Lens-Action.html#v:performs"><code>performs</code></a><a href="http://ekmett.github.com/lens/Control-Lens-Action.html#v:-94-!"><code>^!</code></a></td>-  <td/>-  <td/>-  <td/>-  <td>Perform monadic action(s)</td>-</tr>-<tr><th colspan=5><a href="http://ekmett.github.com/lens/Control-Lens.html">Control.Lens</a> (Indexed)</th></tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-IndexedSetter.html#v:iover"><code>iover</code></a>,<a href="http://ekmett.github.com/lens/Control-Lens-IndexedSetter.html#v:imapOf"><code>imapOf</code></a>,<a href="http://ekmett.github.com/lens/Control-Lens-IndexedSetter.html#v:-37--64--126-"><code>%@~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-IndexedLens.html#v:-60--37--64--126-"><code>&lt;%@~</code></td>-  <td><a href=http://ekmett.github.com/lens/Control-Lens-IndexedSetter.html#v:-37--64--126-"><code>%@=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-IndexedLens.html#v:-60--37--64--61-"><code>&lt;%@=</code></td>-  <td>Update target(s) with access to the index.</td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-Indexed.html#v:withIndex"><code>withIndex</code></a>,<a href="http://ekmett.github.com/lens/Control-Lens-IndexedTraversal.html#v:itraverseOf"><code>itraverseOf</code></a>,<a href="http://ekmett.github.com/lens/Control-Lens-IndexedLens.html#v:-37--37--64--126-"><code>%%@~</code></a></td>-  <td/>-  <td><a href="http://ekmett.github.com/lens/Control-Lens-IndexedLens.html#v:-37--37--64--61-"><code>%%@=</code></a></td>-  <td/>-  <td>Update target(s) with an <code>Applicative</code> or auxillary result with access to the index.</td>-</tr>-<tr><th colspan=5><a href="http://ekmett.github.com/lens/Data-Bits-Lens.html">Data.Bits.Lens</a></th></tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Data-Bits-Lens.html#v:-124--126-"><code>|~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Data-Bits-Lens.html#v:-60--124--126-"><code>&lt;|~</code></td>-  <td><a href="http://ekmett.github.com/lens/Data-Bits-Lens.html#v:-124--61-"><code>|=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Data-Bits-Lens.html#v:-60--124--61-"><code>&lt;|=</code></td>-  <td>Bitwise or target(s)</td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Data-Bits-Lens.html#v:-38--126-"><code>&amp;~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Data-Bits-Lens.html#v:-60--38--126-"><code>&lt;&amp;~</code></td>-  <td><a href="http://ekmett.github.com/lens/Data-Bits-Lens.html#v:-38--61-"><code>&amp;=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Data-Bits-Lens.html#v:-60--38--61-"><code>&lt;&amp;=</code></td>-  <td>Bitwise and target(s)</td>-</tr>-<tr><th colspan=5><a href="http://ekmett.github.com/lens/Data-Monoid-Lens.html">Data.List.Lens</a></th></tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Data-List-Lens.html#v:-43--43--126-"><code>++~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Data-List-Lens.html#v:-60--43--43--126-"><code>&lt;++~</code></td>-  <td><a href="http://ekmett.github.com/lens/Data-List-Lens.html#v:-43--43--61-"><code>++=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Data-List-Lens.html#v:-60--43--43--61-"><code>&lt;++=</code></td>-  <td>Append to target list(s)</td>-</tr>-<tr><th colspan=5><a href="http://ekmett.github.com/lens/Data-Monoid-Lens.html">Data.Monoid.Lens</a></th></tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/Data-Monoid-Lens.html#v:-60--62--126-"><code>&lt;&gt;~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Data-Monoid-Lens.html#v:-60--60--62--126-"><code>&lt;&lt;&gt;~</code></td>-  <td><a href="http://ekmett.github.com/lens/Data-Monoid-Lens.html#v:-60--62--61-"><code>&lt;&gt;=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/Data-Monoid-Lens.html#v:-60--60--62--61-"><code>&lt;&lt;&gt;=</code></td>-  <td><code>mappend</code> to the target monoidal value(s)</td>-</tr>-<tr><th colspan=5><a href="http://ekmett.github.com/lens/System-FilePath-Lens.html">System.FilePath.Lens</a></th></tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/System-FilePath-Lens.html#v:-60--47--62--126-"><code>&lt;/&gt;~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/System-FilePath-Lens.html#v:-60--60--47--62--126-"><code>&lt;&lt;/&gt;~</code></td>-  <td><a href="http://ekmett.github.com/lens/System-FilePath-Lens.html#v:-60--47--62--61-"><code>&lt;/&gt;=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/System-FilePath-Lens.html#v:-60--60--47--62--61-"><code>&lt;&lt;/&gt;=</code></td>-  <td>Append a relative path to a <code>FilePath</code></td>-</tr>-<tr>-  <td><a href="http://ekmett.github.com/lens/System-FilePath-Lens.html#v:-60-.-62--126-"><code>&lt;.&gt;~</code></a></td>-  <td><a href="http://ekmett.github.com/lens/System-FilePath-Lens.html#v:-60--60-.-62--126-"><code>&lt;&lt;.&gt;~</code></td>-  <td><a href="http://ekmett.github.com/lens/System-FilePath-Lens.html#v:-60-.-62--61-"><code>&lt;.&gt;=</code></a></td>-  <td><a href="http://ekmett.github.com/lens/System-FilePath-Lens.html#v:-60--60-.-62--61-"><code>&lt;&lt;.&gt;=</code></td>-  <td>Append a file extension to a <code>FilePath</code></td>-</tr>-</tbody>-</table>+which behaves identically to `_Neither` above. +There is also a fully operational, but simple game of [Pong](https://github.com/ekmett/lens/blob/master/examples/Pong.hs) in the [examples/](https://github.com/ekmett/lens/blob/master/examples/) folder.++There are also a couple of hundred examples distributed throughout the haddock documentation.+ Contact Information -------------------  Contributions and bug reports are welcome! -Please feel free to contact me through github or on the #haskell IRC channel on irc.freenode.net.+Please feel free to contact me through GitHub or on the [#haskell-lens](https://web.libera.chat/#haskell-lens) or [#haskell](https://web.libera.chat/#haskell) IRC channel on Libera Chat.  -Edward Kmett
+ SUPPORT.markdown view
@@ -0,0 +1,10 @@+We currently maintain 2 versions of lens:++We have committed to supporting the 3.7.x branch until GHC 7.8 is released. This version is at 3.7.6 as of the time of this writing. After GHC 7.8 is released we'll continue to+support a version with GHC 7.4 support until the next major GHC release occurs. Practically this means that there should always be some version of lens in a supported configuration+across the last 3 major GHC releases at all times -- counting GHC 7.2 as a technology preview rather than a major release.++We also have committed to keeping the current version of lens up to date and building as part of [stackage](http://github.com/fpco/stackage).++--Edward Kmett+Fri Mar 29 16:11:41 EDT 2013
Setup.lhs view
@@ -1,7 +1,6 @@-#!/usr/bin/runhaskell-> module Main (main) where--> import Distribution.Simple--> main :: IO ()-> main = defaultMain+\begin{code}+module Main (main) where+import Distribution.Simple (defaultMain)+main :: IO ()+main = defaultMain+\end{code}
benchmarks/alongside.hs view
@@ -1,7 +1,10 @@ {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-}+module Main (main) where+ import Control.Applicative import Control.Comonad import Control.Comonad.Store.Class@@ -9,94 +12,92 @@ import Control.Lens import Criterion.Main import Data.Functor.Compose-import Data.Functor.Identity  -- | A finally encoded Store-newtype Experiment c d a = Experiment { runExperiment :: forall f. Functor f => (c -> f d) -> f a }+newtype Experiment a b s = Experiment { runExperiment :: forall f. Functor f => (a -> f b) -> f s } -instance Functor (Experiment c d) where+instance Functor (Experiment a b) where   fmap f (Experiment k) = Experiment (fmap f . k)   {-# INLINE fmap #-} -instance (c ~ d) => Comonad (Experiment c d) where+instance (a ~ b) => Comonad (Experiment a b) where   extract (Experiment m) = runIdentity (m Identity)   {-# INLINE extract #-}   duplicate = duplicateExperiment   {-# INLINE duplicate #-}  -- | 'Experiment' is an indexed 'Comonad'.-duplicateExperiment :: Experiment c e a -> Experiment c d (Experiment d e a)+duplicateExperiment :: Experiment a c s -> Experiment a b (Experiment b c s) duplicateExperiment (Experiment m) = getCompose (m (Compose . fmap placebo . placebo)) {-# INLINE duplicateExperiment #-}  -- | A trivial 'Experiment'.-placebo :: c -> Experiment c d d+placebo :: a -> Experiment a b b placebo i = Experiment (\k -> k i) {-# INLINE placebo #-} -instance (c ~ d) => ComonadStore c (Experiment c d) where+instance (a ~ b) => ComonadStore a (Experiment a b) where   pos m = posExperiment m   peek d m = peekExperiment d m   peeks f m = runIdentity $ runExperiment m (\c -> Identity (f c))   experiment f m = runExperiment m f -posExperiment :: Experiment c d a -> c+posExperiment :: Experiment a b s -> a posExperiment m = getConst (runExperiment m Const) {-# INLINE posExperiment #-} -peekExperiment :: d -> Experiment c d a -> a-peekExperiment d m = runIdentity $ runExperiment m (\_ -> Identity d)+peekExperiment :: b -> Experiment a b s -> s+peekExperiment b m = runIdentity $ runExperiment m (\_ -> Identity b) {-# INLINE peekExperiment #-} -trial :: Lens a b c d -> Lens a' b' c' d' -> Lens (a,a') (b,b') (c,c') (d,d')-trial l r pfq (a,a') = fmap (\(d,b') -> (peekExperiment d x,b')) (getCompose (r (\c' -> Compose $ pfq (posExperiment x, c')) a'))-  where x = l placebo a+trial :: Lens s t a b -> Lens s' t' a' b' -> Lens (s,s') (t,t') (a,a') (b,b')+trial l r pfq (s,s') = fmap (\(b,t') -> (peekExperiment b x,t')) (getCompose (r (\a' -> Compose $ pfq (posExperiment x, a')) s'))+  where x = l placebo s {-# INLINE trial #-} -posContext :: Context c d a -> c-posContext (Context _ c) = c+posContext :: Context a b s -> a+posContext (Context _ a) = a {-# INLINE posContext #-} -peekContext :: d -> Context c d a -> a-peekContext d (Context f _) = f d+peekContext :: b -> Context a b s -> s+peekContext b (Context f _) = f b {-# INLINE peekContext #-}  -- a version of alongside built with Context and product-half :: LensLike (Context c d) a b c d -> Lens a' b' c' d' -> Lens (a,a') (b,b') (c,c') (d,d')-half l r pfq (a,a') = fmap (\(d,b') -> (peekContext d x,b')) (getCompose (r (\c' -> Compose $ pfq (posContext x, c')) a'))-  where x = l (Context id) a+half :: LensLike (Context a b) s t a b -> Lens s' t' a' b' -> Lens (s,s') (t,t') (a,a') (b,b')+half l r pfq (s,s') = fmap (\(b,t') -> (peekContext b x,t')) (getCompose (r (\a' -> Compose $ pfq (posContext x, a')) s'))+  where x = l (Context id) s {-# INLINE half #-} --- alongside' :: Lens a b c d -> Lens a' b' c' d' -> Lens (a,a') (b,b') (c,c') (d,d')+-- alongside' :: Lens s t a b -> Lens s' t' a' b' -> Lens (s,s') (t,t') (a,a') (b,b') -- {-# INLINE alongside'#-} -compound :: Lens a b c d-         -> Lens a' b' c' d'-         -> Lens (a,a') (b,b') (c,c') (d,d')-compound l r = lens (\(a, a') -> (view l a, view r a'))-                    (\(a, a') (b, b') -> (set l b a, set r b' a'))+compound :: Lens' s a+         -> Lens' s' a'+         -> Lens' (s,s') (a,a')+compound l r = lens (\(s, s') -> (view l s, view r s'))+                    (\(s, s') (t, t') -> (set l t s, set r t' s')) {-# INLINE compound #-} -compound5 :: Lens a b c d-          -> Lens a' b' c' d'-          -> Lens a'' b'' c'' d''-          -> Lens a''' b''' c''' d'''-          -> Lens a'''' b'''' c'''' d''''-          -> Lens (a, (a', (a'', (a''', a''''))))-                  (b, (b', (b'', (b''', b''''))))-                  (c, (c', (c'', (c''', c''''))))-                  (d, (d', (d'', (d''', d''''))))+compound5 :: Lens' s a+          -> Lens' s' a'+          -> Lens' s'' a''+          -> Lens' s''' a'''+          -> Lens' s'''' a''''+          -> Lens' (s, (s', (s'', (s''', s''''))))+                  (a, (a', (a'', (a''', a'''')))) compound5 l l' l'' l''' l''''-  = lens (\(a, (a', (a'', (a''', a''''))))-           -> (view l a, (view l' a', (view l'' a'', (view l''' a''', view l'''' a'''')))) )-         (\(a, (a', (a'', (a''', a'''')))) (b, (b', (b'', (b''', b''''))))-           -> (set l b a, (set l' b' a', (set l'' b'' a'', (set l''' b''' a''', set l'''' b'''' a'''')))) )+  = lens (\(s, (s', (s'', (s''', s''''))))+           -> (view l s, (view l' s', (view l'' s'', (view l''' s''', view l'''' s'''')))) )+         (\(s, (s', (s'', (s''', s'''')))) (t, (t', (t'', (t''', t''''))))+           -> (set l t s, (set l' t' s', (set l'' t'' s'', (set l''' t''' s''', set l'''' t'''' s'''')))) ) +main :: IO () main = defaultMain-    [ bench "alongside1" $ nf (view $ alongside _1 _2) (("hi", 1), (2, "there!"))-    , bench "trial1" $ nf (view $ trial _1 _2) (("hi", 1), (2, "there!"))-    , bench "half1" $ nf (view $ half _1 _2) (("hi", 1), (2, "there!"))-    , bench "compound1"  $ nf (view $ compound _1 _2) (("hi", 1), (2, "there!"))+    [ bench "alongside1" $ nf (view $ alongside _1 _2) (("hi", v), (w, "there!"))+    , bench "trial1" $ nf (view $ trial _1 _2) (("hi", v), (w, "there!"))+    , bench "half1" $ nf (view $ half _1 _2) (("hi", v), (w, "there!"))+    , bench "compound1"  $ nf (view $ compound _1 _2) (("hi", v), (w, "there!"))     , bench "alongside5"  $ nf (view $ (alongside _1 (alongside _1 (alongside _1 (alongside _1 _1)))))       ((v,v),((v,v),((v,v),((v,v),(v,v)))))     , bench "trial5"  $ nf (view $ (trial _1 (trial _1 (trial _1 (trial _1 _1)))))@@ -107,3 +108,4 @@       ((v,v),((v,v),((v,v),((v,v),(v,v)))))     ]   where v = 1 :: Int+        w = 2 :: Int
+ benchmarks/folds.hs view
@@ -0,0 +1,123 @@+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE DeriveFunctor #-}+{-# LANGUAGE BangPatterns #-}+module Main (main) where++import qualified Data.ByteString as BS+import qualified Data.Foldable as F+import qualified Data.HashMap.Lazy as HM+import qualified Data.Map as M+import qualified Data.Sequence as S+import qualified Data.Vector as V+import qualified Data.Vector.Unboxed as U++import Data.Vector.Generic.Lens+import Data.ByteString.Lens++import Control.Lens+import Criterion.Main+import Criterion.Types++main :: IO ()+main = defaultMainWith config+  [+    bgroup "vector"+    [ bgroup "toList"+      [ bench "native" $ nf V.toList v+      , bench "each"   $ nf (toListOf each) v+      ]+    , bgroup "itoList"+      [ bench "native"     $ nf (V.toList . V.indexed) v+      , bench "itraversed" $ nf (itoListOf itraversed) v+      ]+    , bgroup "sum"+      [ bench "native" $ whnf V.sum v+      , bench "each"   $ whnf (sumOf each) v+      ]+    ]+  , bgroup "unboxed-vector"+    [ bgroup "toList"+      [ bench "native" $ nf U.toList u+      , bench "each"   $ nf (toListOf each) u+      ]+    , bgroup "itoList"+      [ bench "native"     $ nf (U.toList . U.indexed) u+      , bench "vTraverse" $ nf (itoListOf vectorTraverse) u+      ]+    , bgroup "sum"+      [ bench "native" $ whnf U.sum u+      , bench "each"   $ whnf (sumOf each) u+      ]+    ]+  , bgroup "sequence"+    [ bgroup "toList"+      [ bench "native" $ nf F.toList s+      , bench "each"   $ nf (toListOf each) s+      ]+    , bgroup "itoList"+      [ bench "native"     $ nf (F.toList . S.mapWithIndex (,)) s+      , bench "itraversed" $ nf (itoListOf itraversed) s+      ]+    ]+  , bgroup "bytestring"+    [ bgroup "toList"+      [ bench "native" $ nf BS.unpack b+      , bench "bytes"  $ nf (toListOf bytes) b+      , bench "each"   $ nf (toListOf each) b+      ]+    , bgroup "itoList"+      [ bench "native" $ nf (zip [(0::Int)..] . BS.unpack) b+      , bench "bytes"  $ nf (itoListOf bytes) b+      ]+    ]+  , bgroup "list"+    [ bgroup "toList"+      [ bench "native" $ nf F.toList l+      , bench "each"   $ nf (toListOf each) l+      ]+    , bgroup "itoList"+      [ bench "native"     $ nf (zip [(0::Int)..]) l+      , bench "itraversed" $ nf (itoListOf itraversed) l+      ]+    , bgroup "sum"+      [ bench "native" $ whnf sum l+      , bench "each"   $ whnf (sumOf each) l+      ]+    ]+  , bgroup "map"+    [ bgroup "toList"+      [ bench "native" $ nf F.toList m+      , bench "each"   $ nf itoList m+      ]+    , bgroup "itoList"+      [ bench "native"     $ nf (zip [(0::Int)..] . F.toList) m+      , bench "itraversed" $ nf (itoListOf itraversed) m+      ]+    ]+  , bgroup "hash map"+    [ bgroup "toList"+      [ bench "native" $ nf HM.keys h+      , bench "each"   $ nf (toListOf each) h+      ]+    , bgroup "itoList"+      [ bench "native"     $ nf HM.toList h+      , bench "itoList"    $ nf itoList h+      , bench "itraversed" $ nf (itoListOf itraversed) h+      ]+    , bgroup "sum"+      [ bench "native" $ nf (sum . id . F.toList) h+      , bench "each"   $ nf (sumOf each) h+      ]+    ]+  ]+  where+    config = defaultConfig { timeLimit = 1 }+    l = [0..10000] :: [Int]+    b = BS.pack $ map fromIntegral l+    h = HM.fromList $ zip l l+    m = M.fromList $ zip l l+    s = S.fromList l+    u = U.fromList l+    v = V.fromList l+
benchmarks/plated.hs view
@@ -1,9 +1,9 @@ {-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-}-{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-} {-# OPTIONS_GHC -funbox-strict-fields #-}-import           Control.Applicative+module Main (main) where+ import           Control.Lens import           Control.DeepSeq import           Criterion.Main@@ -14,8 +14,7 @@ import           Data.Generics.Uniplate.Direct ((|*)) import qualified Data.Generics.Uniplate.DataOnly as UniDataOnly #endif-import           GHC.Generics-import           GHC.Generics.Lens as Generic+import           Generics.Deriving hiding (universe)  data Expr  =  Val !Int            |  Var String@@ -24,7 +23,7 @@            |  Sub !Expr !Expr            |  Mul !Expr !Expr            |  Div !Expr !Expr-           deriving (Eq,Show,Data,Typeable,Generic)+           deriving (Eq,Show,Data,Generic)  instance NFData Expr where   rnf (Neg a)   = rnf a@@ -60,11 +59,12 @@ main = defaultMain   [ bench "universe"                           $ nf (map universe) testsExpr   , bench "universeOf plate"                   $ nf (map (universeOf plate)) testsExpr-  , bench "universeOf Generic.tinplate"        $ nf (map (universeOf Generic.tinplate)) testsExpr   , bench "universeOf Data.tinplate"           $ nf (map (universeOf Data.tinplate)) testsExpr   , bench "universeOf Data.template"           $ nf (map (universeOf Data.template)) testsExpr   , bench "universeOf Data.uniplate"           $ nf (map (universeOf Data.uniplate)) testsExpr   , bench "universeOf (cloneTraversal plate)"  $ nf (map (universeOf (cloneTraversal plate))) testsExpr+  , bench "universeOf plate fibExpr"           $ nf (universeOf plate) fibExpr+  , bench "universeOf Data.uniplate fibExpr"   $ nf (universeOf Data.uniplate) fibExpr #ifdef BENCHMARK_UNIPLATE   , bench "Direct.universe"                    $ nf (map Uni.universe) testsExpr   , bench "DataOnly.universe"                  $ nf (map UniDataOnly.universe) testsExpr@@ -73,3 +73,8 @@  testsExpr :: [Expr] testsExpr = [Val 3,Val 2,Val 6,Neg (Neg (Var "dus")),Mul (Div (Add (Val 4) (Var "kxm")) (Sub (Mul (Div (Var "") (Var "")) (Var "w")) (Var "ed"))) (Var "whpd"),Val 6,Val 4,Val 2,Var "a",Val 1,Div (Var "") (Val 0),Var "",Var "",Val (-3),Val 3,Sub (Var "") (Val 2),Neg (Var "dlp"),Div (Val 0) (Var "sd"),Val (-2),Val (-3),Var "g",Mul (Val 3) (Var "i"),Val 1,Var "ul",Div (Add (Var "") (Var "")) (Mul (Div (Val 0) (Neg (Val 0))) (Neg (Neg (Mul (Var "") (Val 0))))),Var "z",Sub (Neg (Add (Var "") (Val 0))) (Var ""),Neg (Sub (Mul (Val 0) (Val 2)) (Val 5)),Val 0,Val 0,Mul (Val (-4)) (Sub (Val 5) (Neg (Div (Div (Val 0) (Sub (Neg (Sub (Val (-3)) (Mul (Mul (Var "ap") (Val 3)) (Add (Add (Add (Var "owre") (Add (Add (Var "avj") (Val 3)) (Var "vhi"))) (Mul (Val 2) (Var "hak"))) (Val 2))))) (Var "nf"))) (Add (Sub (Val 5) (Sub (Var "pkjyh") (Val 2))) (Var "lsiu"))))),Var "u",Val 1,Neg (Add (Add (Var "") (Val 1)) (Sub (Add (Add (Val (-3)) (Mul (Val 1) (Var "pfe"))) (Var "yv")) (Mul (Var "") (Var "jfq")))),Val 2,Div (Div (Div (Div (Var "xrgykq") (Mul (Var "kyfu") (Val 2))) (Sub (Var "v") (Val 0))) (Sub (Val 6) (Val 2))) (Val 3),Var "",Var "",Add (Var "ob") (Sub (Mul (Neg (Val 2)) (Val 6)) (Add (Mul (Val 6) (Sub (Add (Var "wue") (Mul (Var "hgsuj") (Neg (Div (Var "hr") (Var "ozvsb"))))) (Sub (Var "j") (Div (Var "yeyhvq") (Val (-6)))))) (Var "b"))),Div (Add (Div (Div (Neg (Val 4)) (Var "")) (Var "yfx")) (Div (Sub (Var "") (Sub (Var "np") (Mul (Val 3) (Var "mxr")))) (Mul (Var "m") (Var "kkhbf")))) (Neg (Sub (Var "yie") (Val 1))),Neg (Var ""),Var "liuh",Var "pbqg",Var "",Neg (Div (Sub (Add (Val (-1)) (Var "onynvr")) (Neg (Var "tqjsay"))) (Add (Val 4) (Var "yorkb"))),Val 1,Add (Mul (Neg (Div (Val (-1)) (Var "u"))) (Sub (Var "") (Neg (Val 1)))) (Var "h"),Var "",Add (Mul (Sub (Var "em") (Val 0)) (Add (Val (-2)) (Val 1))) (Var ""),Add (Mul (Add (Div (Add (Val 0) (Mul (Mul (Var "e") (Add (Val 1) (Var ""))) (Neg (Neg (Div (Add (Div (Neg (Val 1)) (Div (Val (-1)) (Mul (Add (Div (Val (-1)) (Mul (Mul (Val 1) (Val 1)) (Mul (Var "t") (Val (-1))))) (Val 1)) (Val 1)))) (Add (Neg (Add (Val 0) (Var "k"))) (Mul (Neg (Div (Sub (Sub (Var "u") (Val 1)) (Val 1)) (Sub (Neg (Var "")) (Sub (Var "b") (Val (-1)))))) (Neg (Var ""))))) (Val 0)))))) (Val 0)) (Var "a")) (Var "")) (Val (-1)),Var "xijsnp",Div (Var "h") (Neg (Val 5)),Div (Var "dmzlh") (Add (Val 6) (Val (-2))),Neg (Add (Val 0) (Var "")),Add (Add (Add (Sub (Val 4) (Var "nfse")) (Var "o")) (Add (Val 2) (Div (Var "mtqdx") (Val (-3))))) (Val 3),Neg (Var "c"),Var "sr",Mul (Add (Sub (Neg (Val 1)) (Sub (Div (Add (Sub (Add (Sub (Sub (Var "gd") (Mul (Var "v") (Var "d"))) (Var "")) (Val 1)) (Add (Val 2) (Var ""))) (Var "kk")) (Div (Var "fw") (Add (Val 1) (Var "f")))) (Var ""))) (Val 2)) (Add (Neg (Div (Var "") (Val 0))) (Add (Var "") (Add (Var "s") (Add (Mul (Var "") (Val (-1))) (Val 1))))),Val 1,Var "",Sub (Var "vbnzahx") (Val (-5)),Var "nl",Val 0,Add (Mul (Neg (Mul (Var "") (Var "mvil"))) (Var "")) (Neg (Var "zxl")),Val (-3),Var "",Var "e",Add (Div (Sub (Val 0) (Add (Val 5) (Val 7))) (Mul (Var "") (Var "qz"))) (Val 4),Add (Val (-1)) (Neg (Var "lk")),Add (Add (Var "u") (Mul (Val 1) (Var "h"))) (Sub (Mul (Div (Val 1) (Div (Var "t") (Neg (Var "")))) (Var "")) (Mul (Val 1) (Neg (Div (Neg (Var "")) (Var ""))))),Val 0,Val 0,Val (-7),Mul (Var "") (Val 0),Mul (Add (Val (-6)) (Add (Val 2) (Sub (Div (Var "z") (Var "gbb")) (Var "vddnpsl")))) (Add (Add (Add (Var "") (Sub (Div (Val 3) (Neg (Div (Add (Var "cfvgz") (Add (Sub (Var "htd") (Sub (Var "mhbl") (Var "un"))) (Val 3))) (Val (-3))))) (Var ""))) (Val 5)) (Neg (Mul (Val 0) (Var "sufvvj")))),Sub (Div (Neg (Add (Add (Neg (Add (Var "") (Val 0))) (Var "")) (Sub (Val 0) (Val 0)))) (Val 0)) (Add (Neg (Div (Div (Add (Sub (Add (Add (Neg (Var "")) (Val 0)) (Val 0)) (Add (Neg (Add (Neg (Var "")) (Neg (Val 0)))) (Val 0))) (Div (Val 0) (Val 0))) (Val 0)) (Val 0))) (Var "")),Var "",Sub (Div (Val 0) (Div (Add (Val 1) (Neg (Div (Neg (Var "y")) (Val 0)))) (Var ""))) (Sub (Div (Var "t") (Var "")) (Neg (Var "s"))),Mul (Div (Sub (Var "") (Var "")) (Add (Val 0) (Sub (Div (Var "yr") (Neg (Var "o"))) (Val 1)))) (Var "u"),Var "odmn",Div (Var "uddqy") (Val 3),Var "",Sub (Val 2) (Neg (Val (-1))),Div (Mul (Var "sox") (Val (-3))) (Val (-3)),Var "qv",Var "xmbnts",Var "j",Mul (Val 6) (Mul (Var "fryndq") (Neg (Val 6))),Var "",Var "",Val (-1),Val 7,Add (Var "dg") (Val 1),Neg (Val 1),Val 0,Var "xnm",Sub (Div (Div (Var "miwi") (Var "mbh")) (Val 3)) (Val 3),Neg (Val (-4)),Var "ndubxoa",Var ""]++fibExpr :: Expr+fibExpr = go 11 where+    go :: Int -> Expr+    go n = if n <= 1 then Val 1 else Add (go (n - 1)) (go (n - 2))
+ benchmarks/traversals.hs view
@@ -0,0 +1,107 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE DeriveFunctor #-}+{-# LANGUAGE BangPatterns #-}+{-# OPTIONS_GHC -Wno-orphans #-}+module Main (main) where++import qualified Data.ByteString as BS+import qualified Data.HashMap.Strict as HM+import qualified Data.Map as M+import qualified Data.Sequence as S+import qualified Data.Vector as V+import qualified Data.Vector.Unboxed as U++import Data.Vector.Generic.Lens+import Data.ByteString.Lens++import Control.Lens+import Criterion.Main+import Criterion.Types++main :: IO ()+main = defaultMainWith config+  [+    bgroup "vector"+    [ bgroup "map"+      [ bench "native"     $ nf (V.map (+100)) v+      , bench "itraversed" $ nf (over itraversed (+100)) v+      ]+    , bgroup "imap"+      [ bench "native"     $ nf (V.imap           (\i x -> x + i +100)) v+      , bench "imap"       $ nf (imap             (\i x -> x + i +100)) v+      , bench "itraversed" $ nf (iover itraversed (\i x -> x + i +100)) v+      ]+    ]+  , bgroup "unboxed-vector"+    [ bgroup "map"+      [ bench "native"     $ nf (U.map (+100)) u+      , bench "itraversed" $ nf (over each (+100)) u+      ]+    , bgroup "imap"+      [ bench "native"     $ nf (U.imap (\i x -> x + i +100)) u+      , bench "itraversed" $ nf (iover vectorTraverse (\i x -> x + i) :: U.Vector Int -> U.Vector Int) u+      ]+    ]+  , bgroup "sequence"+    [ bgroup "map"+      [ bench "native" $ nf (fmap            (+100)) s+      , bench "each"   $ nf (over each       (+100)) s+      ]+    , bgroup "imap"+      [ bench "native" $ nf (S.mapWithIndex    (\i x -> x + i +100)) s+      , bench "imap"   $ nf (imap              (\i x -> x + i +100)) s+      ]+    ]+  , bgroup "bytestring"+    [ bgroup "map"+      [ bench "native" $ nf (BS.map     (+100)) b+      , bench "each"   $ nf (over each  (+100)) b+      ]+    , bgroup "imap"+      [+        bench "bytes" $ nf (iover bytes (\i x -> x + fromIntegral i +100)) b+      ]+    ]+  , bgroup "list"+    [ bgroup "map"+      [ bench "native" $ nf (map       (+100)) l+      , bench "each"   $ nf (over each (+100)) l+      ]+    , bgroup "imap"+      [ bench "imap" $ nf (imap (\i x -> x + i +100)) l+      ]+    ]+  , bgroup "map"+    [ bgroup "map"+      [ bench "native"     $ nf (fmap            (+100)) m+      , bench "each"       $ nf (over each       (+100)) m+      , bench "itraversed" $ nf (over itraversed (+100)) m+      ]+    , bgroup "imap"+      [ bench "native" $ nf (M.mapWithKey (\i x -> x + i +100)) m+      , bench "each"   $ nf (imap         (\i x -> x + i +100)) m+      ]+    ]+  , bgroup "hash map"+    [ bgroup "map"+      [ bench "native" $ nf (HM.map    (+100)) h+      , bench "each"   $ nf (over each (+100)) h+      ]+    , bgroup "imap"+      [ bench "native" $ nf (HM.mapWithKey (\i x -> x + i +100)) h+      , bench "imap"   $ nf (imap          (\i x -> x + i +100)) h+      ]+    ]+  ]+  where+    config = defaultConfig { timeLimit = 1 }+    l  = [0..10000] :: [Int]+    xl = [0..100000] :: [Int]+    b  = BS.pack $ map fromIntegral xl+    h  = HM.fromList $ zip l l+    m  = M.fromList $ zip l l+    s  = S.fromList l+    u  = U.fromList xl+    v  = V.fromList l
+ benchmarks/unsafe.hs view
@@ -0,0 +1,59 @@+{-# LANGUAGE BangPatterns #-}+module Main (main) where++import Control.Lens++import Criterion.Main+import Criterion.Types (Config(..))++overS :: ASetter s t a b -> (a -> b) -> s -> t+overS l f = runIdentity . l (Identity . f)+{-# INLINE overS #-}++mappedS :: ASetter [a] [b] a b+mappedS f = Identity . map (runIdentity . f)+{-# INLINE mappedS #-}++overU :: ASetter s t a b -> (a -> b) -> s -> t+overU = over+{-# INLINE overU #-}++mappedU :: ASetter [a] [b] a b+mappedU = mapped+{-# INLINE mappedU #-}+++-- Need to eta-expand for full inlining in the NOINLINE cases?+-- Doesn't seem to make a difference, though.++mapSN :: (a -> b) -> [a] -> [b]+mapSN f l = overS mappedS f l+{-# NOINLINE mapSN #-}++mapSI :: (a -> b) -> [a] -> [b]+mapSI f = overS mappedS f+{-# INLINE mapSI #-}++mapUN :: (a -> b) -> [a] -> [b]+mapUN f l = overU mappedU f l+{-# NOINLINE mapUN #-}++mapUI :: (a -> b) -> [a] -> [b]+mapUI f = overU mappedU f+{-# INLINE mapUI #-}++main :: IO ()+main = do+    let n = 1000+        l = replicate n "hi"; f = length+        --l = replicate n ();   f = (\ _ -> ())+        --l = replicate n ();   f = (\ !_ -> ()) -- strange results+        --l = replicate n ();   f = lazy (\_ -> ())+    defaultMainWith config+        [ bench "map   safe noinline" $ nf (mapSN f) l+        , bench "map   safe   inline" $ nf (mapSI f) l+        , bench "map unsafe noinline" $ nf (mapUN f) l+        , bench "map unsafe   inline" $ nf (mapUI f) l+        ]+  where+    config = defaultConfig { resamples = 1000 }
+ cabal.project view
@@ -0,0 +1,3 @@+packages: .+          ./examples+          ./lens-properties
− config
@@ -1,16 +0,0 @@--- This provides a custom ~/.cabal/config file for use when hackage is down that should work on unix------ This is particularly useful for travis-ci to get it to stop complaining--- about a broken build when everything is still correct on our end.------ This uses Luite Stegeman's mirror of hackage provided by his 'hdiff' site instead------ To enable this, uncomment the before_script in .travis.yml--remote-repo: hdiff.luite.com:http://hdiff.luite.com/packages/archive-remote-repo-cache: ~/.cabal/packages-world-file: ~/.cabal/world-build-summary: ~/.cabal/logs/build.log-remote-build-reporting: anonymous-install-dirs user-install-dirs global
+ examples/.hlint.yaml view
@@ -0,0 +1,4 @@+- arguments: [--cpp-ansi]++- fixity: "infixr 9 ..."+- fixity: "infixl 1 &~"
examples/Aeson.hs view
@@ -11,15 +11,19 @@  import Control.Lens import Data.Aeson-import Data.ByteString.Lazy+import Data.ByteString.Lazy (ByteString) +-- $setup+-- >>> import Control.Lens+ -- |--- >>> 5^.by aeson+-- >>> review aeson 5 -- "5"--- >>> [1,2,3]^.by aeson+-- >>> [1,2,3]^.re aeson -- "[1,2,3]"--- >>> aeson.both +~ 2 $ (2,3)^.by aeson+-- >>> let intPair = simple :: Iso' (Int,Int) (Int, Int)+-- >>> aeson.intPair.both +~ 2 $ (2,3)^.re aeson -- "[4,5]"-aeson, aeson' :: (FromJSON c, ToJSON d) => Projection ByteString ByteString c d-aeson  = projection encode decode-aeson' = projection encode decode'+aeson, aeson' :: (FromJSON a, ToJSON a) => Prism' ByteString a+aeson  = prism' encode decode+aeson' = prism' encode decode'
examples/Plates.hs view
@@ -1,25 +1,25 @@ {-# LANGUAGE MultiParamTypeClasses, DeriveGeneric, DeriveDataTypeable #-}-import Control.Applicative+module Plates where+ import Control.Lens import GHC.Generics import Data.Data-import Data.Data.Lens -data Expr = Var Int | Pos Expr String | Neg Expr | Add Expr Expr deriving (Eq,Ord,Show,Read,Generic,Data,Typeable)-data Stmt = Seq [Stmt] | Sel [Expr] | Let String Expr deriving (Eq,Ord,Show,Read,Generic,Data,Typeable)+data Expr = Var Int | Pos Expr String | Neg Expr | Add Expr Expr deriving (Eq,Ord,Show,Read,Generic,Data)+data Stmt = Seq [Stmt] | Sel [Expr] | Let String Expr deriving (Eq,Ord,Show,Read,Generic,Data)  instance Plated Expr where-  plate f (Var x  ) = pure (Var x)+  plate _ (Var x  ) = pure (Var x)   plate f (Pos x y) = Pos <$> f x <*> pure y   plate f (Neg x  ) = Neg <$> f x   plate f (Add x y) = Add <$> f x <*> f y  instance Plated Stmt where-  plate f (Seq xs) = Seq <$> traverse f xs-  plate f (Sel xs) = pure (Sel xs)-  plate f (Let x y) = pure (Let x y)+  plate f (Seq xs)  = Seq <$> traverse f xs+  plate _ (Sel xs)  = pure (Sel xs)+  plate _ (Let x y) = pure (Let x y) -exprs :: Simple Traversal Stmt Expr+exprs :: Traversal' Stmt Expr exprs f (Seq xs)  = Seq <$> traverse (exprs f) xs exprs f (Sel xs)  = Sel <$> traverse f xs exprs f (Let x y) = Let x <$> f y
examples/Pong.hs view
@@ -2,7 +2,7 @@ ----------------------------------------------------------------------------- -- | -- Module      :  Main--- Copyright   :  (C) 2012 Edward Kmett, nand`+-- Copyright   :  (C) 2012 Edward Kmett, Niklas Haas -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional@@ -12,23 +12,30 @@ ----------------------------------------------------------------------------- module Main where -import Control.Applicative ((<$>), (<*>))-import Control.Lens+import Control.Lens hiding ((:>), at) import Control.Monad.State (State, execState, get) import Control.Monad (when) -import Data.Set (Set, member, empty, insert, delete)+import Data.Set (Set, empty)+import Data.Stream.Infinite (Stream(..)) -import Graphics.Gloss+import Graphics.Gloss hiding (display)+import qualified Graphics.Gloss.Data.Point.Arithmetic as Pt import Graphics.Gloss.Interface.Pure.Game -import System.Random (randomRs, getStdGen)+import System.Random (randomRs, newStdGen)  -- Some global constants +gameSize :: Float gameSize        = 300++windowWidth, windowHeight :: Int windowWidth     = 800 windowHeight    = 600++ballRadius, speedIncrease, losingAccuracy, winningAccuracy,+  initialSpeed, paddleWidth, paddleHeight, paddleSpeed :: Float ballRadius      = 0.02 speedIncrease   = 1.2 losingAccuracy  = 0.9@@ -37,6 +44,8 @@ paddleWidth     = 0.02 paddleHeight    = 0.3 paddleSpeed     = 1++textSize :: Float textSize        = 0.001  -- Pure data type for representing the game state@@ -47,7 +56,7 @@   , _paddle1   :: Float   , _paddle2   :: Float   , _score     :: (Int, Int)-  , _vectors   :: [Vector]+  , _vectors   :: Stream Vector    -- Since gloss doesn't cover this, we store the set of pressed keys   , _keys      :: Set Key@@ -57,11 +66,14 @@ makeLenses ''Pong  -- Renamed tuple lenses for enhanced clarity with points/vectors+_x :: Field1 s t a b => Lens s t a b _x = _1++_y :: Field2 s t a b => Lens s t a b _y = _2  initial :: Pong-initial = Pong (0, 0) (0, 0) 0 0 (0, 0) [] empty+initial = Pong (0, 0) (0, 0) 0 0 (0, 0) (return (0, 0)) empty  -- Calculate the y position at which the ball will next hit (on player2's side) hitPos :: Point -> Vector -> Float@@ -100,7 +112,7 @@ updateBall :: Float -> State Pong () updateBall time = do   (u, v) <- use ballSpeed-  ballPos += (time * u, time * v)+  ballPos %= (Pt.+ (time * u, time * v))    -- Make sure it doesn't leave the playing area   ballPos.both %= clamp ballRadius@@ -173,7 +185,7 @@ -- Retrieve a speed from the list, dropping it in the process nextSpeed :: State Pong Vector nextSpeed = do-  v:vs <- use vectors+  v:>vs <- use vectors   vectors .= vs   return v @@ -191,7 +203,7 @@   ]   where     paddleX = 1 + paddleWidth/2-    p `at` (x,y) = translate x y p; infixr 1 `at`+    po `at` (x,y) = translate x y po; infixr 1 `at`  drawPaddle :: Picture drawPaddle = rectangleSolid paddleWidth paddleHeight@@ -210,8 +222,9 @@  -- The main program action +main :: IO () main = do-  v:vs <- startingSpeeds+  v:>vs <- startingSpeeds   let world = ballSpeed .~ v $ vectors .~ vs $ initial   play display backColor fps world draw handle update @@ -222,12 +235,16 @@  -- Generate the random list of starting speeds -startingSpeeds :: IO [Vector]+startingSpeeds :: IO (Stream Vector) startingSpeeds = do-  rs <- randomRs (-initialSpeed, initialSpeed) <$> getStdGen-  return . interleave $ filter ((> 0.2) . abs) rs+  rs <- randomRs (-initialSpeed, initialSpeed) <$> newStdGen+  return . listToStream . interleave $ filter ((> 0.2) . abs) rs    where     interleave :: [a] -> [(a,a)]     interleave (x:y:xs) = (x,y) : interleave xs     interleave _        = []++    -- Assumes the list is infinite.+    listToStream :: [a] -> Stream a+    listToStream = foldr (:>) (error "Finite list")
+ examples/Setup.lhs view
@@ -0,0 +1,7 @@+#!/usr/bin/runhaskell+> module Main (main) where++> import Distribution.Simple++> main :: IO ()+> main = defaultMain
+ examples/Turtle.hs view
@@ -0,0 +1,65 @@+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE DeriveDataTypeable #-}+-- | A simple Turtle-graphics demonstration for modeling the location of a turtle.+--+-- This is based on the code presented by Seth Tisue at the Boston Area Scala+-- Enthusiasts meeting during his lens talk.+--+-- Usage:+--+-- > def & forward 10 & down & color .~ red % turn (pi/2) & forward 5+module Turtle where++import Control.Lens+import Data.Default.Class++data Point = Point+  { __x, __y :: Double+  } deriving (Eq,Show)++makeClassy ''Point++instance Default Point where+  def = Point def def++data Color = Color+  { __r, __g, __b :: Int+  } deriving (Eq,Show)++makeClassy ''Color++red :: Color+red = Color 255 0 0++instance Default Color where+  def = Color def def def++data Turtle = Turtle+  { _tPoint  :: Point+  , _tColor  :: Color+  , _heading :: Double+  , _penDown :: Bool+  } deriving (Eq,Show)++makeClassy ''Turtle++instance Default Turtle where+  def = Turtle def def def False++instance HasPoint Turtle where+  point = tPoint++instance HasColor Turtle where+  color = tColor++forward :: Double -> Turtle -> Turtle+forward d t =+  t & _y +~ d * cos (t^.heading)+    & _x +~ d * sin (t^.heading)++turn :: Double -> Turtle -> Turtle+turn d = heading +~ d++up, down :: Turtle -> Turtle+up   = penDown .~ False+down = penDown .~ True
examples/lens-examples.cabal view
@@ -2,30 +2,68 @@ category:      Data, Lenses version:       0.1 license:       BSD3-cabal-version: >= 1.8+cabal-version: >= 1.10 license-file:  LICENSE-author:        nand+author:        Niklas Haas maintainer:    Edward A. Kmett <ekmett@gmail.com> stability:     provisional homepage:      http://github.com/ekmett/lens/ bug-reports:   http://github.com/ekmett/lens/issues copyright:     Copyright (C) 2012 Edward A. Kmett synopsis:      Lenses, Folds and Traversals-description:   Pong Example+description:   Lenses, Folds and Traversals+               .+               Pong Example  build-type:    Simple-tested-with:   GHC == 7.4.1+tested-with:   GHC == 8.0.2+             , GHC == 8.2.2+             , GHC == 8.4.4+             , GHC == 8.6.5+             , GHC == 8.8.4+             , GHC == 8.10.7+             , GHC == 9.0.2+             , GHC == 9.2.8+             , GHC == 9.4.8+             , GHC == 9.6.7+             , GHC == 9.8.4+             , GHC == 9.10.3+             , GHC == 9.12.2+             , GHC == 9.14.1  source-repository head   type: git-  location: git://github.com/ekmett/lens.git+  location: https://github.com/ekmett/lens.git -executable pong+flag pong+  default: True++library+  exposed-modules:+    Aeson+    Plates+    Turtle   build-depends:-    base       == 4.*,-    containers >= 0.4.2 && < 0.6,-    gloss      == 1.7.*,+    aeson,+    base       >= 4.9      && < 5,+    bytestring >= 0.9.1.10 && < 0.13,+    data-default-class,+    lens+  default-language: Haskell2010+  ghc-options: -Wall++executable lens-pong+  if !flag(pong)+    buildable: False++  build-depends:+    base       >= 4.9   && < 5,+    containers >= 0.4   && < 0.9,+    gloss      >= 1.12  && < 1.14,     lens,-    mtl        >= 2.0.1 && < 2.2,-    random     == 1.0.*+    mtl        >= 2.0.1 && < 2.4,+    random     >= 1.0   && < 1.4,+    streams    >= 3.3   && < 4   main-is: Pong.hs+  default-language: Haskell2010+  ghc-options: -Wall
+ images/Hierarchy.png view

binary file changed (absent → 209295 bytes)

+ images/overview.png view

binary file changed (absent → 239100 bytes)

+ include/lens-common.h view
@@ -0,0 +1,26 @@+#ifndef LENS_COMMON_H+#define LENS_COMMON_H++#if __GLASGOW_HASKELL__ >= 806+# define KVS(kvs) kvs+#else+# define KVS(kvs)+#endif++#ifndef MIN_VERSION_base+#define MIN_VERSION_base(x,y,z) 1+#endif++#ifndef MIN_VERSION_bytestring+#define MIN_VERSION_bytestring(x,y,z) 1+#endif++#ifndef MIN_VERSION_containers+#define MIN_VERSION_containers(x,y,z) 1+#endif++#ifndef MIN_VERSION_template_haskell+#define MIN_VERSION_template_haskell(x,y,z) 1+#endif++#endif
+ lens-properties/.hlint.yaml view
@@ -0,0 +1,4 @@+- arguments: [--cpp-ansi]+- ignore: { name: Use camelCase }+- fixity: "infixr 9 ..."+- fixity: "infixl 1 &~"
+ lens-properties/CHANGELOG.markdown view
@@ -0,0 +1,17 @@+next [????.??.??]+-----------------+* Drop support for GHC 7.10 and older.++4.11.1+------+* Update version bounds.++4.0+---++* Initial release containing the properties:+  * `isIso`+  * `isLens`+  * `isPrism`+  * `isSetter`+  * `isTraversal`
+ lens-properties/LICENSE view
@@ -0,0 +1,27 @@+Copyright (c) 2012-2014, Edward Kmett+Copyright (c) 2014, Oliver Charles++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++    * Redistributions of source code must retain the above copyright+      notice, this list of conditions and the following disclaimer.++    * Redistributions in binary form must reproduce the above+      copyright notice, this list of conditions and the following+      disclaimer in the documentation and/or other materials provided+      with the distribution.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ lens-properties/Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ lens-properties/lens-properties.cabal view
@@ -0,0 +1,51 @@+name:          lens-properties+category:      Data, Lenses+version:       4.11.1+license:       BSD3+cabal-version: >= 1.10+license-file:  LICENSE+author:        Edward Kmett and Oliver Charles+maintainer:    Edward Kmett <ekmett@gmail.com>+stability:     provisional+homepage:      http://github.com/ekmett/lens/+bug-reports:   http://github.com/ekmett/lens/issues+copyright:     Copyright (C) 2012-2015 Edward A. Kmett, Copyright (C) 2014 Oliver Charles+synopsis:      QuickCheck properties for lens+description:   QuickCheck properties for lens.+build-type:    Simple+tested-with:   GHC == 8.0.2+             , GHC == 8.2.2+             , GHC == 8.4.4+             , GHC == 8.6.5+             , GHC == 8.8.4+             , GHC == 8.10.7+             , GHC == 9.0.2+             , GHC == 9.2.8+             , GHC == 9.4.8+             , GHC == 9.6.7+             , GHC == 9.8.4+             , GHC == 9.10.3+             , GHC == 9.12.2+             , GHC == 9.14.1++extra-source-files:+  .hlint.yaml+  CHANGELOG.markdown++source-repository head+  type: git+  location: https://github.com/ekmett/lens.git++library+  build-depends:+    base         >= 4.9 && < 5,+    lens         >= 4   && < 6,+    QuickCheck   >= 2.4 && < 2.18,+    transformers >= 0.2 && < 0.7++  exposed-modules:+    Control.Lens.Properties++  hs-source-dirs: src+  ghc-options: -Wall+  default-language: Haskell2010
+ lens-properties/src/Control/Lens/Properties.hs view
@@ -0,0 +1,116 @@+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE LiberalTypeSynonyms #-}+{-# LANGUAGE ScopedTypeVariables #-}+-- | A collection of properties that can be tested with QuickCheck, to guarantee+-- that you are working with valid 'Lens'es, 'Setter's, 'Traversal's, 'Iso's and+-- 'Prism's.+module Control.Lens.Properties+    ( isLens+    , isTraversal+    , isSetter+    , isIso+    , isPrism+    ) where++import Control.Lens+import Data.Functor.Compose+import Test.QuickCheck++--------------------------------------------------------------------------------+-- | A 'Setter' is only legal if the following 3 laws hold:+--+-- 1. @set l y (set l x a) ≡ set l y a@+--+-- 2. @over l id ≡ id@+--+-- 3. @over l f . over l g ≡ over l (f . g)@+isSetter :: (Arbitrary s, Arbitrary a, CoArbitrary a, Show s, Show a, Eq s, Function a)+         => Setter' s a -> Property+isSetter l = setter_id l .&. setter_composition l .&. setter_set_set l+++--------------------------------------------------------------------------------+-- | A 'Traversal' is only legal if it is a valid 'Setter' (see 'isSetter' for+-- what makes a 'Setter' valid), and the following laws hold:+--+-- 1. @t pure ≡ pure@+--+-- 2. @fmap (t f) . t g ≡ getCompose . t (Compose . fmap f . g)@+isTraversal :: (Arbitrary s, Arbitrary a, CoArbitrary a, Show s, Show a, Eq s, Function a)+         => Traversal' s a -> Property+isTraversal l = isSetter l .&. traverse_pureMaybe l .&. traverse_pureList l+                  .&. do as <- arbitrary+                         bs <- arbitrary+                         t <- arbitrary+                         return $ traverse_compose l (\x -> as++[x]++bs)+                                                     (\x -> if t then Just x else Nothing)+++--------------------------------------------------------------------------------+-- | A 'Lens' is only legal if it is a valid 'Traversal' (see 'isTraversal' for+-- what this means), and if the following laws hold:+--+-- 1. @view l (set l b a)  ≡ b@+--+-- 2. @set l (view l a) a  ≡ a@+--+-- 3. @set l c (set l b a) ≡ set l c a@+isLens :: (Arbitrary s, Arbitrary a, CoArbitrary a, Show s, Show a, Eq s, Eq a, Function a)+       => Lens' s a -> Property+isLens l = lens_set_view l .&. lens_view_set l .&. isTraversal l+++--------------------------------------------------------------------------------+isIso :: (Arbitrary s, Arbitrary a, CoArbitrary s, CoArbitrary a, Show s, Show a, Eq s, Eq a, Function s, Function a)+      => Iso' s a -> Property+isIso l = iso_hither l .&. iso_yon l .&. isLens l .&. isLens (from l)+++--------------------------------------------------------------------------------+isPrism :: (Arbitrary s, Arbitrary a, CoArbitrary a, Show s, Show a, Eq s, Eq a, Function a)+      => Prism' s a -> Property+isPrism l = isTraversal l .&. prism_yin l .&. prism_yang l+++--------------------------------------------------------------------------------+-- The first setter law:+setter_id :: Eq s => Setter' s a -> s -> Bool+setter_id l s = over l id s == s++--  The second setter law:+setter_composition :: Eq s => Setter' s a -> s -> Fun a a -> Fun a a -> Bool+setter_composition l s (Fun _ f) (Fun _ g) = over l f (over l g s) == over l (f . g) s++lens_set_view :: Eq s => Lens' s a -> s -> Bool+lens_set_view l s = set l (view l s) s == s++lens_view_set :: Eq a => Lens' s a -> s -> a -> Bool+lens_view_set l s a = view l (set l a s) == a++setter_set_set :: Eq s => Setter' s a -> s -> a -> a -> Bool+setter_set_set l s a b = set l b (set l a s) == set l b s++iso_hither :: Eq s => AnIso' s a -> s -> Bool+iso_hither l s = s ^.cloneIso l.from l == s++iso_yon :: Eq a => AnIso' s a -> a -> Bool+iso_yon l a = a^.from l.cloneIso l == a++prism_yin :: Eq a => Prism' s a -> a -> Bool+prism_yin l a = preview l (review l a) == Just a++prism_yang :: Eq s => Prism' s a -> s -> Bool+prism_yang l s = maybe s (review l) (preview l s) == s++traverse_pure :: forall f s a. (Applicative f, Eq (f s)) => LensLike' f s a -> s -> Bool+traverse_pure l s = l pure s == (pure s :: f s)++traverse_pureMaybe :: Eq s => LensLike' Maybe s a -> s -> Bool+traverse_pureMaybe = traverse_pure++traverse_pureList :: Eq s => LensLike' [] s a -> s -> Bool+traverse_pureList = traverse_pure++traverse_compose :: (Applicative f, Applicative g, Eq (f (g s)))+                    => Traversal' s a -> (a -> g a) -> (a -> f a) -> s -> Bool+traverse_compose t f g s = (fmap (t f) . t g) s == (getCompose . t (Compose . fmap f . g)) s
lens.cabal view
@@ -1,15 +1,31 @@ name:          lens-category:      Data, Lenses-version:       2.9-license:       BSD3-cabal-version: >= 1.8+category:      Data, Lenses, Generics+version:       5.3.6+license:       BSD2+cabal-version: 1.18 license-file:  LICENSE author:        Edward A. Kmett maintainer:    Edward A. Kmett <ekmett@gmail.com> stability:     provisional homepage:      http://github.com/ekmett/lens/ bug-reports:   http://github.com/ekmett/lens/issues-copyright:     Copyright (C) 2012 Edward A. Kmett+copyright:     Copyright (C) 2012-2016 Edward A. Kmett+build-type:    Simple+-- build-tools:   cpphs+tested-with:   GHC == 8.0.2+             , GHC == 8.2.2+             , GHC == 8.4.4+             , GHC == 8.6.5+             , GHC == 8.8.4+             , GHC == 8.10.7+             , GHC == 9.0.2+             , GHC == 9.2.8+             , GHC == 9.4.8+             , GHC == 9.6.7+             , GHC == 9.8.4+             , GHC == 9.10.3+             , GHC == 9.12.2+             , GHC == 9.14.1 synopsis:      Lenses, Folds and Traversals description:   This package comes \"Batteries Included\" with many useful lenses for the types@@ -20,28 +36,29 @@   families of getters, folds, isomorphisms, traversals, setters and lenses and their   indexed variants.   .-  An overview, with a large number of examples can be found in the README.+  An overview, with a large number of examples can be found in the <https://github.com/ekmett/lens#lens-lenses-folds-and-traversals README>.   .-  <https://github.com/ekmett/lens#lens-lenses-folds-and-traversals>+  An introductory video on the style of code used in this library by Simon Peyton Jones is available from <https://archive.org/details/lenses-compositional-data-access-and-manipulation-simon-peyton-jones-at-haskell- Internet Archive>.   .-  More information on the care and feeding of lenses, including a brief tutorial and motivation-  for their types can be found on the lens wiki.+  A video on how to use lenses and how they are constructed is available on <http://youtu.be/cefnmjtAolY?hd=1 youtube>.   .-  <https://github.com/ekmett/lens/wiki>+  Slides for that second talk can be obtained from <http://comonad.com/haskell/Lenses-Folds-and-Traversals-NYC.pdf comonad.com>.   .-  A small game that manages its state using lenses can be found in the example folder.+  More information on the care and feeding of lenses, including a brief tutorial and motivation+  for their types can be found on the <https://github.com/ekmett/lens/wiki lens wiki>.   .-  <https://github.com/ekmett/lens/blob/master/examples/Pong.hs>+  A small game of @pong@ and other more complex examples that manage their state using lenses can be found in the <https://github.com/ekmett/lens/blob/master/examples/ example folder>.   .   /Lenses, Folds and Traversals/   .-  The core of this hierarchy looks like:+  With some signatures simplified, the core of the hierarchy of lens-like constructions looks like:   .-  <<https://github.com/ekmett/lens/wiki/images/Hierarchy-2.9.png>>   .-  You can compose any two elements of the hierarchy above using (.) from the Prelude, and you can-  use any element of the hierarchy as any type it links to above it.+  <<https://raw.githubusercontent.com/ekmett/lens/master/images/Hierarchy.png>>   .+  You can compose any two elements of the hierarchy above using @(.)@ from the @Prelude@, and you can+  use any element of the hierarchy as any type it linked to above it.+  .   The result is their lowest upper bound in the hierarchy (or an error if that bound doesn't exist).   .   For instance:@@ -55,17 +72,17 @@   If you want to provide lenses and traversals for your own types in your own libraries, then you   can do so without incurring a dependency on this (or any other) lens package at all.   .-  e.g. for a data type:+  /e.g./ for a data type:   .   > data Foo a = Foo Int Int a   .   You can define lenses such as   .-  > -- bar :: Simple Lens (Foo a) Int-  > bar :: Functor f => (Int -> f Int) -> Foo a -> f Foo a+  > -- bar :: Lens' (Foo a) Int+  > bar :: Functor f => (Int -> f Int) -> Foo a -> f (Foo a)   > bar f (Foo a b c) = fmap (\a' -> Foo a' b c) (f a)   .-  > -- baz :: Lens (Foo a) (Foo b) a b+  > -- quux :: Lens (Foo a) (Foo b) a b   > quux :: Functor f => (a -> f b) -> Foo a -> f (Foo b)   > quux f (Foo a b c) = fmap (Foo a b) (f c)   .@@ -73,33 +90,40 @@   .   And you can define a traversal of multiple fields with 'Control.Applicative.Applicative':   .-  > -- traverseBarAndBaz :: Simple Traversal (Foo a) Int+  > -- traverseBarAndBaz :: Traversal' (Foo a) Int   > traverseBarAndBaz :: Applicative f => (Int -> f Int) -> Foo a -> f (Foo a)   > traverseBarAndBaz f (Foo a b c) = Foo <$> f a <*> f b <*> pure c   .   What is provided in this library is a number of stock lenses and traversals for   common haskell types, a wide array of combinators for working them, and more-  exotic functionality, (e.g. getters, setters, indexed folds, isomorphisms).+  exotic functionality, (/e.g./ getters, setters, indexed folds, isomorphisms). -build-type:    Simple-tested-with:   GHC == 7.4.1, GHC == 7.6.0, GHC == 7.7.20120822, GHC == 7.7.20120830 extra-source-files:-  .travis.yml-  .ghci   .gitignore+  .hlint.yaml   .vim.custom-  config+  cabal.project   examples/LICENSE   examples/lens-examples.cabal-  examples/Pong.hs-  examples/Plates.hs-  examples/Aeson.hs-  README.markdown+  examples/*.hs+  examples/*.lhs+  examples/.hlint.yaml+  include/*.h+  lens-properties/.hlint.yaml+  lens-properties/CHANGELOG.markdown+  lens-properties/LICENSE+  lens-properties/Setup.hs+  lens-properties/lens-properties.cabal+  AUTHORS.markdown   CHANGELOG.markdown+  README.markdown+  SUPPORT.markdown+extra-doc-files:+  images/*.png  source-repository head   type: git-  location: git://github.com/ekmett/lens.git+  location: https://github.com/ekmett/lens.git  -- Enable benchmarking against Neil Mitchell's uniplate library for comparative performance analysis. Defaults to being turned off to avoid -- the extra dependency.@@ -109,15 +133,6 @@   default: False   manual: True --- Enable template haskell. Disable this at your own risk and for testing only.------ cabal configure -f-template-haskell is an /unsuppported/ configuration.------ Clients of this library can and should expect this to be turned on.-flag template-haskell-  default: True-  manual: True- -- Generate inline pragmas when using template-haskell. This defaults to enabled, but you can -- -- > cabal install lens -f-inlining@@ -128,55 +143,131 @@   manual: True   default: True --- Some 7.6.1-rc1 users report their TH still uses old style inline pragmas. This lets them turn on inlining.-flag old-inline-pragmas+-- Make the test suites dump their template-haskell splices.+flag dump-splices   default: False   manual: True --- Make the test suites dump their template-haskell splices.-flag dump-splices+-- You can disable the hunit test suite with -f-test-hunit+flag test-hunit+  default: True+  manual: True++-- Build the properties test if we're building tests+flag test-properties+  default: True+  manual: True++flag test-templates+  default: True+  manual: True++-- Assert that we are trustworthy when we can+flag trustworthy+  default: True+  manual: True++-- Attempt a parallel build with GHC 7.8+flag j   default: False   manual: True  library   build-depends:-    base                 >= 4.4      && < 5,-    bytestring           >= 0.9.1.10 && < 0.11,-    comonad              == 3.0.*,-    comonad-transformers == 3.0.*,-    comonads-fd          == 3.0.*,-    containers           >= 0.4.2    && < 0.6,-    hashable             == 1.1.*,-    mtl                  >= 2.1.1    && < 2.2,-    text                 >= 0.11     && < 0.12,-    transformers         >= 0.3      && < 0.4,-    unordered-containers >= 0.2      && < 0.3+    array                         >= 0.5.0.0  && < 0.6,+    assoc                         >= 1.0.2    && < 1.2,+    base                          >= 4.9      && < 5,+    base-orphans                  >= 0.5.2    && < 1,+    bifunctors                    >= 5.5.7    && < 6,+    bytestring                    >= 0.10.4.0 && < 0.13,+    call-stack                    >= 0.1      && < 0.5,+    comonad                       >= 5.0.7    && < 6,+    containers                    >= 0.5.5.1  && < 0.9,+    contravariant                 >= 1.4      && < 2,+    distributive                  >= 0.5.1    && < 1,+    exceptions                    >= 0.8.2.1  && < 1,+    filepath                      >= 1.2.0.0  && < 1.6,+    free                          >= 5.1.5    && < 6,+    hashable                      >= 1.2.7.0  && < 1.6,+    indexed-traversable           >= 0.1      && < 0.2,+    indexed-traversable-instances >= 0.1      && < 0.2,+    kan-extensions                >= 5        && < 6,+    mtl                           >= 2.2.1    && < 2.4,+    parallel                      >= 3.2.1.0  && < 3.4,+    profunctors                   >= 5.5.2    && < 6,+    reflection                    >= 2.1      && < 3,+    semigroupoids                 >= 5.0.1    && < 7,+    strict                        >= 0.4      && < 0.6,+    tagged                        >= 0.8.6    && < 1,+    template-haskell              >= 2.11.1.0 && < 2.25,+    text                          >= 1.2.3.0  && < 2.2,+    th-abstraction                >= 0.4.1    && < 0.8,+    these                         >= 1.1.1.1  && < 1.3,+    transformers                  >= 0.5.0.0  && < 0.7,+    unordered-containers          >= 0.2.10   && < 0.3,+    vector                        >= 0.12.1.2 && < 0.14 +  -- Control.Lens as the first module, so cabal repl loads it.   exposed-modules:-    Control.Exception.Lens     Control.Lens-    Control.Lens.Action++  exposed-modules:+    Control.Exception.Lens+    Control.Lens.At     Control.Lens.Combinators+    Control.Lens.Cons+    Control.Lens.Each+    Control.Lens.Empty+    Control.Lens.Equality+    Control.Lens.Extras     Control.Lens.Fold     Control.Lens.Getter     Control.Lens.Indexed-    Control.Lens.IndexedGetter-    Control.Lens.IndexedFold-    Control.Lens.IndexedLens-    Control.Lens.IndexedSetter-    Control.Lens.IndexedTraversal     Control.Lens.Internal+    Control.Lens.Internal.Bazaar+    Control.Lens.Internal.ByteString+    Control.Lens.Internal.Context+    Control.Lens.Internal.CTypes+    Control.Lens.Internal.Deque+    Control.Lens.Internal.Doctest+    Control.Lens.Internal.Exception+    Control.Lens.Internal.FieldTH+    Control.Lens.Internal.PrismTH+    Control.Lens.Internal.Fold+    Control.Lens.Internal.Getter+    Control.Lens.Internal.Indexed+    Control.Lens.Internal.Instances+    Control.Lens.Internal.Iso+    Control.Lens.Internal.Level+    Control.Lens.Internal.List+    Control.Lens.Internal.Magma+    Control.Lens.Internal.Prism+    Control.Lens.Internal.Profunctor+    Control.Lens.Internal.Review+    Control.Lens.Internal.Setter+    Control.Lens.Internal.TH+    Control.Lens.Internal.Zoom     Control.Lens.Iso-    Control.Lens.Isomorphic+    Control.Lens.Lens+    Control.Lens.Level+    Control.Lens.Operators     Control.Lens.Plated-    Control.Lens.Projection-    Control.Lens.Representable+    Control.Lens.Prism+    Control.Lens.Profunctor+    Control.Lens.Reified+    Control.Lens.Review     Control.Lens.Setter+    Control.Lens.TH     Control.Lens.Traversal     Control.Lens.Tuple     Control.Lens.Type-    Control.Lens.WithIndex+    Control.Lens.Unsound+    Control.Lens.Wrapped     Control.Lens.Zoom+    Control.Monad.Error.Lens+    Control.Parallel.Strategies.Lens+    Control.Seq.Lens+    Data.Array.Lens     Data.Bits.Lens     Data.ByteString.Lens     Data.ByteString.Strict.Lens@@ -187,7 +278,7 @@     Data.HashSet.Lens     Data.IntSet.Lens     Data.List.Lens-    Data.Monoid.Lens+    Data.Map.Lens     Data.Sequence.Lens     Data.Set.Lens     Data.Text.Lens@@ -195,123 +286,201 @@     Data.Text.Lazy.Lens     Data.Tree.Lens     Data.Typeable.Lens+    Data.Vector.Lens+    Data.Vector.Generic.Lens+    GHC.Generics.Lens+    System.Exit.Lens+    System.FilePath.Lens+    System.IO.Error.Lens+    Language.Haskell.TH.Lens+    Numeric.Lens+    Numeric.Natural.Lens -  if flag(template-haskell)-    build-depends: template-haskell >= 2.4 && < 2.9-    exposed-modules: Control.Lens.TH Language.Haskell.TH.Lens-  else-    cpp-options: -DDISABLE_TEMPLATE_HASKELL+  other-modules:+    Control.Lens.Internal.Prelude -  -- platform-  build-depends:   array >= 0.3.0.2 && < 0.5-  exposed-modules: Data.Array.Lens+  if flag(trustworthy) && impl(ghc)+    other-extensions: Trustworthy+    cpp-options: -DTRUSTWORTHY=1 -  build-depends:   filepath >= 1.2.0.0 && < 1.4-  exposed-modules: System.FilePath.Lens+  if flag(inlining)+    cpp-options: -DINLINING -  build-depends:   parallel >= 3.1.0.1 && < 3.3-  exposed-modules: Control.Parallel.Strategies.Lens Control.Seq.Lens+  if flag(j)+    ghc-options: -j4 -  if impl(ghc>=7.6.0.20120810)-    if flag(old-inline-pragmas)-      cpp-options: -DOLD_INLINE_PRAGMAS+  ghc-options: -Wall -Wtabs -O2 -fdicts-cheap -funbox-strict-fields -fmax-simplifier-iterations=10+               -Wno-trustworthy-safe -Wmissing-pattern-synonym-signatures -Wno-redundant-constraints -  if !flag(inlining)-    cpp-options: -DOMIT_INLINING+  hs-source-dirs: src -  if impl(ghc>=7.4)-    other-extensions: Trustworthy-    build-depends: ghc-prim-    exposed-modules: GHC.Generics.Lens+  include-dirs: include -  ghc-options: -Wall -fwarn-tabs -O2 -fdicts-cheap -funbox-strict-fields-  hs-source-dirs: src+  default-language: Haskell2010 +  -- future proof, whether the field will be comma separated or not.+  x-docspec-extra-packages: simple-reflect+  x-docspec-extra-packages: deepseq+ -- Verify that Template Haskell expansion works test-suite templates   type: exitcode-stdio-1.0   main-is: templates.hs-  build-depends:-    base,-    lens+  other-modules:+    BigRecord+    T799+    T917+    T972+  if impl(ghc >= 9.2)+    other-modules:+      T1024   ghc-options: -Wall -threaded+  hs-source-dirs: tests+  default-language: Haskell2010+   if flag(dump-splices)     ghc-options: -ddump-splices-  if impl(ghc<7.6.1)-    ghc-options: -Werror-  hs-source-dirs: tests +  if !flag(test-templates)+    buildable: False+  else+    build-depends: base, lens+ -- Verify the properties of lenses with QuickCheck test-suite properties   type: exitcode-stdio-1.0   main-is: properties.hs-  build-depends:-    base,-    lens,-    QuickCheck   >= 2.4 && < 2.6,-    transformers-  ghc-options: -w -threaded-  hs-source-dirs: tests+  other-modules:+    Control.Lens.Properties+  ghc-options: -Wall -threaded -rtsopts -with-rtsopts=-N+  hs-source-dirs:+    tests+    lens-properties/src+  include-dirs: include+  default-language: Haskell2010+  if !flag(test-properties)+    buildable: False+  else+    build-depends:+      base,+      lens,+      QuickCheck >= 2.4,+      tasty >= 1.4 && < 1.6,+      tasty-quickcheck >= 0.10 && < 0.12,+      transformers  test-suite hunit   type: exitcode-stdio-1.0   main-is: hunit.hs-  build-depends:-    base,-    containers,-    HUnit == 1.2.*,-    lens,-    mtl,-    test-framework == 0.6.*,-    test-framework-hunit == 0.2.*,-    test-framework-th == 0.2.*-  ghc-options: -w -threaded+  ghc-options: -Wall -threaded -rtsopts -with-rtsopts=-N   hs-source-dirs: tests+  default-language: Haskell2010 --- Verify the results of the examples+  if !flag(test-hunit)+    buildable: False+  else+    build-depends:+      base,+      containers,+      lens,+      mtl,+      text,+      bytestring,+      tasty >= 1.4 && < 1.6,+      tasty-hunit >= 0.10 && < 0.11++-- We need this dummy test-suite to add simple-reflect to the install plan+--+-- When cabal-install's extra-packages support becomes widely available+-- (i.e. after 3.4 release), we can remove this test-suite. test-suite doctests-  type:    exitcode-stdio-1.0-  main-is: doctests.hs-  build-depends:-    base,-    directory >= 1.0 && < 1.3,-    doctest >= 0.9 && <= 0.10,-    filepath-  ghc-options: -Wall -threaded-  if impl(ghc<7.6.1)-    ghc-options: -Werror-  hs-source-dirs: tests+  type:              exitcode-stdio-1.0+  main-is:           doctests.hs+  hs-source-dirs:    tests+  default-language:  Haskell2010 +  build-depends: base <5, deepseq, simple-reflect >= 0.3.1+ -- Basic benchmarks for the uniplate-style combinators benchmark plated-  type: exitcode-stdio-1.0-  main-is: plated.hs+  type:             exitcode-stdio-1.0+  main-is:          plated.hs+  ghc-options:      -Wall -O2 -threaded -fdicts-cheap -funbox-strict-fields+  hs-source-dirs:   benchmarks+  default-language: Haskell2010   build-depends:     base,     comonad,     criterion,     deepseq,-    ghc-prim,+    generic-deriving,     lens,     transformers-  ghc-options: -Wall -O2 -threaded -fdicts-cheap -funbox-strict-fields-  hs-source-dirs: benchmarks+   if flag(benchmark-uniplate)     build-depends: uniplate >= 1.6.7 && < 1.7     cpp-options: -DBENCHMARK_UNIPLATE --- Basic benchmarks for the uniplate-style combinators+-- Benchmarking alongside variants benchmark alongside-  type: exitcode-stdio-1.0-  main-is: alongside.hs+  type:             exitcode-stdio-1.0+  main-is:          alongside.hs+  ghc-options:      -Wall -O2 -threaded -fdicts-cheap -funbox-strict-fields+  hs-source-dirs:   benchmarks+  default-language: Haskell2010   build-depends:     base,-    comonad,-    comonads-fd,+    comonad >= 4,     criterion,     deepseq,-    ghc-prim,     lens,     transformers-  ghc-options: -w -O2 -threaded -fdicts-cheap -funbox-strict-fields-  hs-source-dirs: benchmarks++-- Benchmarking folds+benchmark folds+  type:             exitcode-stdio-1.0+  main-is:          folds.hs+  ghc-options:      -Wall -O2 -threaded -fdicts-cheap -funbox-strict-fields+  hs-source-dirs:   benchmarks+  default-language: Haskell2010+  build-depends:+    base,+    criterion,+    containers,+    bytestring,+    unordered-containers,+    vector,+    lens++-- Benchmarking traversals+benchmark traversals+  type:             exitcode-stdio-1.0+  main-is:          traversals.hs+  ghc-options:      -Wall -O2 -threaded -fdicts-cheap -funbox-strict-fields+  hs-source-dirs:   benchmarks+  default-language: Haskell2010+  build-depends:+    base,+    criterion,+    containers,+    deepseq,+    bytestring,+    unordered-containers,+    vector,+    lens++-- Benchmarking unsafe implementation strategies+benchmark unsafe+  type:             exitcode-stdio-1.0+  main-is:          unsafe.hs+  ghc-options:      -Wall -O2 -threaded -fdicts-cheap -funbox-strict-fields+  hs-source-dirs:   benchmarks+  default-language: Haskell2010+  build-depends:+    base,+    comonad >= 4,+    criterion >= 1,+    deepseq,+    generic-deriving,+    lens,+    transformers
src/Control/Exception/Lens.hs view
@@ -1,29 +1,1484 @@-{-# LANGUAGE FlexibleContexts #-}--------------------------------------------------------------------------------- |--- Module      :  Control.Exception.Lens--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  Control.Exception---------------------------------------------------------------------------------module Control.Exception.Lens-  ( exception-  ) where--import Control.Exception-import Control.Lens---- |--- Traverse the strongly typed 'Exception' contained in 'SomeException' where the type of your function matches--- the desired 'Exception'.------ @--- exception :: ('Applicative' f, 'Exception' a, 'Exception' b)---           => (a -> f b) -> 'SomeException' -> f 'SomeException'--- @-exception :: (Exception a, Exception b) => Projection SomeException SomeException a b-exception = projection SomeException fromException-{-# INLINE exception #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE NoMonomorphismRestriction #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-}++#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-}+#endif++#include "lens-common.h"++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Exception.Lens+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  Control.Exception+--+-- @Control.Exception@ provides an example of a large open hierarchy+-- that we can model with prisms and isomorphisms.+--+-- Additional combinators for working with 'IOException' results can+-- be found in "System.IO.Error.Lens".+--+-- The combinators in this module have been generalized to work with+-- 'MonadCatch' instead of just 'Prelude.IO'. This enables them to be used+-- more easily in 'Monad' transformer stacks.+----------------------------------------------------------------------------+module Control.Exception.Lens+  (+  -- * Handling+    catching, catching_+  , handling, handling_+  -- * Trying+  , trying, trying_+  -- * Throwing+  , throwing+  , throwing_+  , throwingM+  , throwingTo+  -- * Mapping+  , mappedException, mappedException'+  -- * Exceptions+  , exception+  , pattern Exception+  -- * Exception Handlers+  , Handleable(..)+  -- ** IOExceptions+  , AsIOException(..)+  , pattern IOException_+  -- ** Arithmetic Exceptions+  , AsArithException(..)+  , _Overflow, _Underflow, _LossOfPrecision, _DivideByZero, _Denormal+  , _RatioZeroDenominator+  , pattern ArithException_+  , pattern Overflow_+  , pattern Underflow_+  , pattern LossOfPrecision_+  , pattern DivideByZero_+  , pattern Denormal_+  , pattern RatioZeroDenominator_+  -- ** Array Exceptions+  , AsArrayException(..)+  , _IndexOutOfBounds+  , _UndefinedElement+  , pattern ArrayException_+  , pattern IndexOutOfBounds_+  , pattern UndefinedElement_+  -- ** Assertion Failed+  , AsAssertionFailed(..)+  , pattern AssertionFailed__+  , pattern AssertionFailed_+  -- ** Async Exceptions+  , AsAsyncException(..)+  , _StackOverflow+  , _HeapOverflow+  , _ThreadKilled+  , _UserInterrupt+  , pattern AsyncException_+  , pattern StackOverflow_+  , pattern HeapOverflow_+  , pattern ThreadKilled_+  , pattern UserInterrupt_+  -- ** Non-Termination+  , AsNonTermination(..)+  , pattern NonTermination__+  , pattern NonTermination_+  -- ** Nested Atomically+  , AsNestedAtomically(..)+  , pattern NestedAtomically__+  , pattern NestedAtomically_+  -- ** Blocked Indefinitely+  -- *** on MVar+  , AsBlockedIndefinitelyOnMVar(..)+  , pattern BlockedIndefinitelyOnMVar__+  , pattern BlockedIndefinitelyOnMVar_+  -- *** on STM+  , AsBlockedIndefinitelyOnSTM(..)+  , pattern BlockedIndefinitelyOnSTM__+  , pattern BlockedIndefinitelyOnSTM_+  -- ** Deadlock+  , AsDeadlock(..)+  , pattern Deadlock__+  , pattern Deadlock_+  -- ** No Such Method+  , AsNoMethodError(..)+  , pattern NoMethodError__+  , pattern NoMethodError_+  -- ** Pattern Match Failure+  , AsPatternMatchFail(..)+  , pattern PatternMatchFail__+  , pattern PatternMatchFail_+  -- ** Record+  , AsRecConError(..)+  , AsRecSelError(..)+  , AsRecUpdError(..)+  , pattern RecConError__+  , pattern RecConError_+  , pattern RecSelError__+  , pattern RecSelError_+  , pattern RecUpdError__+  , pattern RecUpdError_+  -- ** Error Call+  , AsErrorCall(..)+  , pattern ErrorCall__+  , pattern ErrorCall_+  -- ** Allocation Limit Exceeded+  , AsAllocationLimitExceeded(..)+  , pattern AllocationLimitExceeded__+  , pattern AllocationLimitExceeded_+  -- ** Type Error+  , AsTypeError(..)+  , pattern TypeError__+  , pattern TypeError_+#if MIN_VERSION_base(4,10,0)+  -- ** Compaction Failed+  , AsCompactionFailed(..)+  , pattern CompactionFailed__+  , pattern CompactionFailed_+#endif+  -- * Handling Exceptions+  , AsHandlingException(..)+  , pattern HandlingException__+  , pattern HandlingException_+  ) where++import Control.Applicative+import Control.Monad+import Control.Monad.IO.Class+import Control.Monad.Catch as Catch+import Control.Exception as Exception hiding (try, tryJust, catchJust)+import Control.Lens+import Control.Lens.Internal.Exception+import Data.Monoid+import GHC.Conc (ThreadId)+import Prelude+  ( const, either, flip, id+  , (.)+  , Maybe(..), Either(..), String+  , Bool(..)+  )++{-+$setup+>>> :set -XNoOverloadedStrings+>>> :set -XScopedTypeVariables+>>> import Control.Lens+>>> import Control.Applicative+>>> :m + Control.Exception Control.Monad Data.List Prelude+#if MIN_VERSION_base(4,20,0)+>>> :m + Control.Exception.Context+#endif+-}++------------------------------------------------------------------------------+-- Exceptions as Prisms+------------------------------------------------------------------------------++-- | Traverse the strongly typed t'Exception' contained in 'SomeException' where the type of your function matches+-- the desired t'Exception'.+--+-- @+-- 'exception' :: ('Applicative' f, t'Exception' a)+--           => (a -> f a) -> 'SomeException' -> f 'SomeException'+-- @+exception :: Exception a => Prism' SomeException a+exception = prism' toException fromException+{-# INLINE exception #-}++pattern Exception :: Exception a => a -> SomeException+pattern Exception e <- (preview exception -> Just e) where+  Exception e = review exception e++------------------------------------------------------------------------------+-- Catching+------------------------------------------------------------------------------++-- | Catch exceptions that match a given t'Prism' (or any t'Fold', really).+--+-- >>> catching _AssertionFailed (assert False (return "uncaught")) $ \ _ -> return "caught"+-- "caught"+--+-- @+-- 'catching' :: 'MonadCatch' m => 'Prism'' 'SomeException' a     -> m r -> (a -> m r) -> m r+-- 'catching' :: 'MonadCatch' m => 'Lens'' 'SomeException' a      -> m r -> (a -> m r) -> m r+-- 'catching' :: 'MonadCatch' m => 'Traversal'' 'SomeException' a -> m r -> (a -> m r) -> m r+-- 'catching' :: 'MonadCatch' m => 'Iso'' 'SomeException' a       -> m r -> (a -> m r) -> m r+-- 'catching' :: 'MonadCatch' m => t'Getter' 'SomeException' a    -> m r -> (a -> m r) -> m r+-- 'catching' :: 'MonadCatch' m => t'Fold' 'SomeException' a      -> m r -> (a -> m r) -> m r+-- @+catching :: MonadCatch m => Getting (First a) SomeException a -> m r -> (a -> m r) -> m r+catching l = catchJust (preview l)+{-# INLINE catching #-}++-- | Catch exceptions that match a given t'Prism' (or any t'Getter'), discarding+-- the information about the match. This is particularly useful when you have+-- a @'Prism'' e ()@ where the result of the t'Prism' or t'Fold' isn't+-- particularly valuable, just the fact that it matches.+--+-- >>> catching_ _AssertionFailed (assert False (return "uncaught")) $ return "caught"+-- "caught"+--+-- @+-- 'catching_' :: 'MonadCatch' m => 'Prism'' 'SomeException' a     -> m r -> m r -> m r+-- 'catching_' :: 'MonadCatch' m => 'Lens'' 'SomeException' a      -> m r -> m r -> m r+-- 'catching_' :: 'MonadCatch' m => 'Traversal'' 'SomeException' a -> m r -> m r -> m r+-- 'catching_' :: 'MonadCatch' m => 'Iso'' 'SomeException' a       -> m r -> m r -> m r+-- 'catching_' :: 'MonadCatch' m => t'Getter' 'SomeException' a    -> m r -> m r -> m r+-- 'catching_' :: 'MonadCatch' m => t'Fold' 'SomeException' a      -> m r -> m r -> m r+-- @+catching_ :: MonadCatch m => Getting (First a) SomeException a -> m r -> m r -> m r+catching_ l a b = catchJust (preview l) a (const b)+{-# INLINE catching_ #-}++------------------------------------------------------------------------------+-- Handling+------------------------------------------------------------------------------++-- | A version of 'catching' with the arguments swapped around; useful in+-- situations where the code for the handler is shorter.+--+-- >>> handling _NonTermination (\_ -> return "caught") $ throwIO NonTermination+-- "caught"+--+-- @+-- 'handling' :: 'MonadCatch' m => 'Prism'' 'SomeException' a     -> (a -> m r) -> m r -> m r+-- 'handling' :: 'MonadCatch' m => 'Lens'' 'SomeException' a      -> (a -> m r) -> m r -> m r+-- 'handling' :: 'MonadCatch' m => 'Traversal'' 'SomeException' a -> (a -> m r) -> m r -> m r+-- 'handling' :: 'MonadCatch' m => 'Iso'' 'SomeException' a       -> (a -> m r) -> m r -> m r+-- 'handling' :: 'MonadCatch' m => t'Fold' 'SomeException' a      -> (a -> m r) -> m r -> m r+-- 'handling' :: 'MonadCatch' m => t'Getter' 'SomeException' a    -> (a -> m r) -> m r -> m r+-- @+handling :: MonadCatch m => Getting (First a) SomeException a -> (a -> m r) -> m r -> m r+handling l = flip (catching l)+{-# INLINE handling #-}++-- | A version of 'catching_' with the arguments swapped around; useful in+-- situations where the code for the handler is shorter.+--+-- >>> handling_ _NonTermination (return "caught") $ throwIO NonTermination+-- "caught"+--+-- @+-- 'handling_' :: 'MonadCatch' m => 'Prism'' 'SomeException' a     -> m r -> m r -> m r+-- 'handling_' :: 'MonadCatch' m => 'Lens'' 'SomeException' a      -> m r -> m r -> m r+-- 'handling_' :: 'MonadCatch' m => 'Traversal'' 'SomeException' a -> m r -> m r -> m r+-- 'handling_' :: 'MonadCatch' m => 'Iso'' 'SomeException' a       -> m r -> m r -> m r+-- 'handling_' :: 'MonadCatch' m => t'Getter' 'SomeException' a    -> m r -> m r -> m r+-- 'handling_' :: 'MonadCatch' m => t'Fold' 'SomeException' a      -> m r -> m r -> m r+-- @+handling_ :: MonadCatch m => Getting (First a) SomeException a -> m r -> m r -> m r+handling_ l = flip (catching_ l)+{-# INLINE handling_ #-}++------------------------------------------------------------------------------+-- Trying+------------------------------------------------------------------------------++-- | A variant of 'Control.Exception.try' that takes a t'Prism' (or any t'Fold') to select which+-- exceptions are caught (c.f. 'Control.Exception.tryJust', 'Control.Exception.catchJust'). If the+-- t'Exception' does not match the predicate, it is re-thrown.+--+-- @+-- 'trying' :: 'MonadCatch' m => 'Prism''     'SomeException' a -> m r -> m ('Either' a r)+-- 'trying' :: 'MonadCatch' m => 'Lens''      'SomeException' a -> m r -> m ('Either' a r)+-- 'trying' :: 'MonadCatch' m => 'Traversal'' 'SomeException' a -> m r -> m ('Either' a r)+-- 'trying' :: 'MonadCatch' m => 'Iso''       'SomeException' a -> m r -> m ('Either' a r)+-- 'trying' :: 'MonadCatch' m => t'Getter'    'SomeException' a -> m r -> m ('Either' a r)+-- 'trying' :: 'MonadCatch' m => t'Fold'      'SomeException' a -> m r -> m ('Either' a r)+-- @+trying :: MonadCatch m => Getting (First a) SomeException a -> m r -> m (Either a r)+trying l = tryJust (preview l)+{-# INLINE trying #-}++-- | A version of 'trying' that discards the specific exception thrown.+--+-- @+-- 'trying_' :: 'MonadCatch' m => 'Prism''     'SomeException' a -> m r -> m (Maybe r)+-- 'trying_' :: 'MonadCatch' m => 'Lens''      'SomeException' a -> m r -> m (Maybe r)+-- 'trying_' :: 'MonadCatch' m => 'Traversal'' 'SomeException' a -> m r -> m (Maybe r)+-- 'trying_' :: 'MonadCatch' m => 'Iso''       'SomeException' a -> m r -> m (Maybe r)+-- 'trying_' :: 'MonadCatch' m => t'Getter'    'SomeException' a -> m r -> m (Maybe r)+-- 'trying_' :: 'MonadCatch' m => t'Fold'      'SomeException' a -> m r -> m (Maybe r)+-- @+trying_ :: MonadCatch m => Getting (First a) SomeException a -> m r -> m (Maybe r)+trying_ l m = preview _Right `liftM` trying l m+{-# INLINE trying_ #-}++------------------------------------------------------------------------------+-- Throwing+------------------------------------------------------------------------------++-- | Throw an t'Exception' described by a t'Prism'. Exceptions may be thrown from+-- purely functional code, but may only be caught within the 'Prelude.IO' 'Monad'.+--+-- @+-- 'throwing' l ≡ 'reviews' l 'throw'+-- @+--+-- @+-- 'throwing' :: 'Prism'' 'SomeException' t -> t -> r+-- 'throwing' :: 'Iso'' 'SomeException' t   -> t -> r+-- @+throwing :: AReview SomeException b -> b -> r+throwing l = reviews l Exception.throw+{-# INLINE throwing #-}++-- | Similar to 'throwing' but specialised for the common case of+--   error constructors with no arguments.+--+-- @+-- data MyError = Foo | Bar+-- makePrisms ''MyError+-- 'throwing_' _Foo :: 'Control.Monad.Error.Class.MonadError' MyError m => m a+-- @+throwing_ :: AReview SomeException () -> m x+throwing_ l = throwing l ()+{-# INLINE throwing_ #-}++-- | A variant of 'throwing' that can only be used within the 'Prelude.IO' 'Monad'+-- (or any other 'MonadCatch' instance) to throw an t'Exception' described+-- by a t'Prism'.+--+-- Although 'throwingM' has a type that is a specialization of the type of+-- 'throwing', the two functions are subtly different:+--+-- @+-- 'throwing' l e \`seq\` x  ≡ 'throwing' e+-- 'throwingM' l e \`seq\` x ≡ x+-- @+--+-- The first example will cause the t'Exception' @e@ to be raised, whereas the+-- second one won't. In fact, 'throwingM' will only cause an t'Exception' to+-- be raised when it is used within the 'MonadCatch' instance. The 'throwingM'+-- variant should be used in preference to 'throwing' to raise an t'Exception'+-- within the 'Monad' because it guarantees ordering with respect to other+-- monadic operations, whereas 'throwing' does not.+--+-- @+-- 'throwingM' l ≡ 'reviews' l 'CatchIO.throw'+-- @+--+-- @+-- 'throwingM' :: 'MonadThrow' m => 'Prism'' 'SomeException' t -> t -> m r+-- 'throwingM' :: 'MonadThrow' m => 'Iso'' 'SomeException' t   -> t -> m r+-- @+throwingM :: MonadThrow m => AReview SomeException b -> b -> m r+throwingM l = reviews l throwM+{-# INLINE throwingM #-}++-- | 'throwingTo' raises an t'Exception' specified by a t'Prism' in the target thread.+--+-- @+-- 'throwingTo' thread l ≡ 'reviews' l ('throwTo' thread)+-- @+--+-- @+-- 'throwingTo' :: 'ThreadId' -> 'Prism'' 'SomeException' t -> t -> m a+-- 'throwingTo' :: 'ThreadId' -> 'Iso'' 'SomeException' t   -> t -> m a+-- @+throwingTo :: MonadIO m => ThreadId -> AReview SomeException b -> b -> m ()+throwingTo tid l = reviews l (liftIO . throwTo tid)+{-# INLINE throwingTo #-}++----------------------------------------------------------------------------+-- Mapping+----------------------------------------------------------------------------++-- | This t'Setter' can be used to purely map over the t'Exception's an+-- arbitrary expression might throw; it is a variant of 'mapException' in+-- the same way that 'mapped' is a variant of 'fmap'.+--+-- > 'mapException' ≡ 'over' 'mappedException'+--+-- This view that every Haskell expression can be regarded as carrying a bag+-- of t'Exception's is detailed in “A Semantics for Imprecise Exceptions” by+-- Peyton Jones & al. at PLDI ’99.+--+-- The following maps failed assertions to arithmetic overflow:+--+-- >>> handling _Overflow (\_ -> return "caught") $ assert False (return "uncaught") & mappedException %~ \ (AssertionFailed _) -> Overflow+-- "caught"+mappedException :: (Exception e, Exception e') => Setter s s e e'+mappedException = sets mapException+{-# INLINE mappedException #-}++-- | This is a type restricted version of 'mappedException', which avoids+-- the type ambiguity in the input t'Exception' when using 'set'.+--+-- The following maps any exception to arithmetic overflow:+--+-- >>> handling _Overflow (\_ -> return "caught") $ assert False (return "uncaught") & mappedException' .~ Overflow+-- "caught"+mappedException' :: Exception e' => Setter s s SomeException e'+mappedException' = mappedException+{-# INLINE mappedException' #-}++----------------------------------------------------------------------------+-- IOException+----------------------------------------------------------------------------++-- | Exceptions that occur in the 'Prelude.IO' 'Monad'. An 'IOException' records a+-- more specific error type, a descriptive string and maybe the handle that was+-- used when the error was flagged.+--+-- Due to their richer structure relative to other exceptions, these have+-- a more carefully overloaded signature.+class AsIOException t where+  -- | Unfortunately the name 'GHC.IO.Exception.ioException' is taken by @base@ for+  -- throwing IOExceptions.+  --+  -- @+  -- '_IOException' :: 'Prism'' 'IOException' 'IOException'+  -- '_IOException' :: 'Prism'' 'SomeException' 'IOException'+  -- @+  --+  -- Many combinators for working with an 'IOException' are available+  -- in "System.IO.Error.Lens".+  _IOException :: Prism' t IOException++instance AsIOException IOException where+  _IOException = id+  {-# INLINE _IOException #-}++instance AsIOException SomeException where+  _IOException = exception+  {-# INLINE _IOException #-}++pattern IOException_ :: AsIOException s => IOException -> s+pattern IOException_ a <- (preview _IOException -> Just a) where+  IOException_ a = review _IOException a++----------------------------------------------------------------------------+-- ArithException+----------------------------------------------------------------------------++-- | Arithmetic exceptions.+class AsArithException t where+  -- |+  -- @+  -- '_ArithException' :: 'Prism'' 'ArithException' 'ArithException'+  -- '_ArithException' :: 'Prism'' 'SomeException'  'ArithException'+  -- @+  _ArithException :: Prism' t ArithException++pattern ArithException_ :: AsArithException s => ArithException -> s+pattern ArithException_ a <- (preview _ArithException -> Just a) where+  ArithException_ a = review _ArithException a++instance AsArithException ArithException where+  _ArithException = id+  {-# INLINE _ArithException #-}++instance AsArithException SomeException where+  _ArithException = exception+  {-# INLINE _ArithException #-}++-- | Handle arithmetic '_Overflow'.+--+-- @+-- '_Overflow' ≡ '_ArithException' '.' '_Overflow'+-- @+--+-- @+-- '_Overflow' :: 'Prism'' 'ArithException' 'ArithException'+-- '_Overflow' :: 'Prism'' 'SomeException'  'ArithException'+-- @+_Overflow :: AsArithException t => Prism' t ()+_Overflow = _ArithException . dimap seta (either id id) . right' . rmap (Overflow <$) where+  seta Overflow = Right ()+  seta t        = Left  (pure t)+{-# INLINE _Overflow #-}++pattern Overflow_ :: AsArithException s => s+pattern Overflow_ <- (has _Overflow -> True) where+  Overflow_ = review _Overflow ()++-- | Handle arithmetic '_Underflow'.+--+-- @+-- '_Underflow' ≡ '_ArithException' '.' '_Underflow'+-- @+--+-- @+-- '_Underflow' :: 'Prism'' 'ArithException' 'ArithException'+-- '_Underflow' :: 'Prism'' 'SomeException'  'ArithException'+-- @+_Underflow :: AsArithException t => Prism' t ()+_Underflow = _ArithException . dimap seta (either id id) . right' . rmap (Underflow <$) where+  seta Underflow = Right ()+  seta t        = Left  (pure t)+{-# INLINE _Underflow #-}++pattern Underflow_ :: AsArithException s => s+pattern Underflow_ <- (has _Underflow -> True) where+  Underflow_ = review _Underflow ()++-- | Handle arithmetic loss of precision.+--+-- @+-- '_LossOfPrecision' ≡ '_ArithException' '.' '_LossOfPrecision'+-- @+--+-- @+-- '_LossOfPrecision' :: 'Prism'' 'ArithException' 'ArithException'+-- '_LossOfPrecision' :: 'Prism'' 'SomeException'  'ArithException'+-- @+_LossOfPrecision :: AsArithException t => Prism' t ()+_LossOfPrecision = _ArithException . dimap seta (either id id) . right' . rmap (LossOfPrecision <$) where+  seta LossOfPrecision = Right ()+  seta t        = Left  (pure t)+{-# INLINE _LossOfPrecision #-}++pattern LossOfPrecision_ :: AsArithException s => s+pattern LossOfPrecision_ <- (has _LossOfPrecision -> True) where+  LossOfPrecision_ = review _LossOfPrecision ()++-- | Handle division by zero.+--+-- @+-- '_DivideByZero' ≡ '_ArithException' '.' '_DivideByZero'+-- @+--+-- @+-- '_DivideByZero' :: 'Prism'' 'ArithException' 'ArithException'+-- '_DivideByZero' :: 'Prism'' 'SomeException'  'ArithException'+-- @+_DivideByZero :: AsArithException t => Prism' t ()+_DivideByZero = _ArithException . dimap seta (either id id) . right' . rmap (DivideByZero <$) where+  seta DivideByZero = Right ()+  seta t        = Left  (pure t)+{-# INLINE _DivideByZero #-}++pattern DivideByZero_ :: AsArithException s => s+pattern DivideByZero_ <- (has _DivideByZero -> True) where+  DivideByZero_ = review _DivideByZero ()++-- | Handle exceptional _Denormalized floating pure.+--+-- @+-- '_Denormal' ≡ '_ArithException' '.' '_Denormal'+-- @+--+-- @+-- '_Denormal' :: 'Prism'' 'ArithException' 'ArithException'+-- '_Denormal' :: 'Prism'' 'SomeException'  'ArithException'+-- @+_Denormal :: AsArithException t => Prism' t ()+_Denormal = _ArithException . dimap seta (either id id) . right' . rmap (Denormal <$) where+  seta Denormal = Right ()+  seta t        = Left  (pure t)+{-# INLINE _Denormal #-}++pattern Denormal_ :: AsArithException s => s+pattern Denormal_ <- (has _Denormal -> True) where+  Denormal_ = review _Denormal ()++-- |+--+-- @+-- '_RatioZeroDenominator' ≡ '_ArithException' '.' '_RatioZeroDenominator'+-- @+--+-- @+-- '_RatioZeroDenominator' :: 'Prism'' 'ArithException' 'ArithException'+-- '_RatioZeroDenominator' :: 'Prism'' 'SomeException'  'ArithException'+-- @+_RatioZeroDenominator :: AsArithException t => Prism' t ()+_RatioZeroDenominator = _ArithException . dimap seta (either id id) . right' . rmap (RatioZeroDenominator <$) where+  seta RatioZeroDenominator = Right ()+  seta t        = Left  (pure t)+{-# INLINE _RatioZeroDenominator #-}++pattern RatioZeroDenominator_ :: AsArithException s => s+pattern RatioZeroDenominator_ <- (has _RatioZeroDenominator -> True) where+  RatioZeroDenominator_ = review _RatioZeroDenominator ()++----------------------------------------------------------------------------+-- ArrayException+----------------------------------------------------------------------------++-- | Exceptions generated by array operations.+class AsArrayException t where+  -- | Extract information about an 'ArrayException'.+  --+  -- @+  -- '_ArrayException' :: 'Prism'' 'ArrayException' 'ArrayException'+  -- '_ArrayException' :: 'Prism'' 'SomeException'  'ArrayException'+  -- @+  _ArrayException :: Prism' t ArrayException++instance AsArrayException ArrayException where+  _ArrayException = id+  {-# INLINE _ArrayException #-}++instance AsArrayException SomeException where+  _ArrayException = exception+  {-# INLINE _ArrayException #-}++pattern ArrayException_ :: AsArrayException s => ArrayException -> s+pattern ArrayException_ e <- (preview _ArrayException -> Just e) where+  ArrayException_ e = review _ArrayException e++-- | An attempt was made to index an array outside its declared bounds.+--+-- @+-- '_IndexOutOfBounds' ≡ '_ArrayException' '.' '_IndexOutOfBounds'+-- @+--+-- @+-- '_IndexOutOfBounds' :: 'Prism'' 'ArrayException' 'String'+-- '_IndexOutOfBounds' :: 'Prism'' 'SomeException'  'String'+-- @+_IndexOutOfBounds :: AsArrayException t => Prism' t String+_IndexOutOfBounds = _ArrayException . dimap seta (either id id) . right' . rmap (fmap IndexOutOfBounds) where+  seta (IndexOutOfBounds r) = Right r+  seta t                    = Left  (pure t)+{-# INLINE _IndexOutOfBounds #-}++pattern IndexOutOfBounds_ :: AsArrayException s => String -> s+pattern IndexOutOfBounds_ e <- (preview _IndexOutOfBounds -> Just e) where+  IndexOutOfBounds_ e = review _IndexOutOfBounds e++-- | An attempt was made to evaluate an element of an array that had not been initialized.+--+-- @+-- '_UndefinedElement' ≡ '_ArrayException' '.' '_UndefinedElement'+-- @+--+-- @+-- '_UndefinedElement' :: 'Prism'' 'ArrayException' 'String'+-- '_UndefinedElement' :: 'Prism'' 'SomeException'  'String'+-- @+_UndefinedElement :: AsArrayException t => Prism' t String+_UndefinedElement = _ArrayException . dimap seta (either id id) . right' . rmap (fmap UndefinedElement) where+  seta (UndefinedElement r) = Right r+  seta t                    = Left  (pure t)+{-# INLINE _UndefinedElement #-}++pattern UndefinedElement_ :: AsArrayException s => String -> s+pattern UndefinedElement_ e <- (preview _UndefinedElement -> Just e) where+  UndefinedElement_ e = review _UndefinedElement e++----------------------------------------------------------------------------+-- AssertionFailed+----------------------------------------------------------------------------++-- | 'assert' was applied to 'Prelude.False'.+class AsAssertionFailed t where+  -- |+  -- @+  -- '__AssertionFailed' :: 'Prism'' 'AssertionFailed' 'AssertionFailed'+  -- '__AssertionFailed' :: 'Prism'' 'SomeException'   'AssertionFailed'+  -- @+  __AssertionFailed :: Prism' t AssertionFailed++  {- | This t'Exception' contains provides information about what assertion failed in the 'String'.++  @+  '_AssertionFailed' :: 'Prism'' 'AssertionFailed' 'String'+  '_AssertionFailed' :: 'Prism'' 'SomeException'   'String'+  @++#if MIN_VERSION_base(4,20,0)+  >>> handling exception (\ (ExceptionWithContext ctxt (_ :: AssertionFailed)) -> "caught" <$ guard ("<interactive>" `isInfixOf` displayExceptionContext ctxt) ) $ assert False (return "uncaught")+  "caught"+#else+  -- >>> handling _AssertionFailed (\ xs -> "caught" <$ guard ("<interactive>" `isInfixOf` xs) ) $ assert False (return "uncaught")+  -- "caught"+#endif+  -}+  _AssertionFailed :: Prism' t String+  _AssertionFailed = __AssertionFailed._AssertionFailed+  {-# INLINE _AssertionFailed #-}++instance AsAssertionFailed AssertionFailed where+  __AssertionFailed = id+  {-# INLINE __AssertionFailed #-}++  _AssertionFailed = _Wrapping AssertionFailed+  {-# INLINE _AssertionFailed #-}++instance AsAssertionFailed SomeException where+  __AssertionFailed = exception+  {-# INLINE __AssertionFailed #-}++pattern AssertionFailed__ :: AsAssertionFailed s => AssertionFailed -> s+pattern AssertionFailed__ e <- (preview __AssertionFailed -> Just e) where+  AssertionFailed__ e = review __AssertionFailed e++pattern AssertionFailed_ :: AsAssertionFailed s => String -> s+pattern AssertionFailed_ e <- (preview _AssertionFailed -> Just e) where+  AssertionFailed_ e = review _AssertionFailed e++----------------------------------------------------------------------------+-- AsyncException+----------------------------------------------------------------------------++-- | Asynchronous exceptions.+class AsAsyncException t where+  -- | There are several types of 'AsyncException'.+  --+  -- @+  -- '_AsyncException' :: 'Equality'' 'AsyncException' 'AsyncException'+  -- '_AsyncException' :: 'Prism''    'SomeException'  'AsyncException'+  -- @+  _AsyncException :: Prism' t AsyncException++instance AsAsyncException AsyncException where+  _AsyncException = id+  {-# INLINE _AsyncException #-}++instance AsAsyncException SomeException where+  _AsyncException = exception+  {-# INLINE _AsyncException #-}++pattern AsyncException_ :: AsAsyncException s => AsyncException -> s+pattern AsyncException_ e <- (preview _AsyncException -> Just e) where+  AsyncException_ e = review _AsyncException e++-- | The current thread's stack exceeded its limit. Since an t'Exception' has+-- been raised, the thread's stack will certainly be below its limit again,+-- but the programmer should take remedial action immediately.+--+-- @+-- '_StackOverflow' :: 'Prism'' 'AsyncException' ()+-- '_StackOverflow' :: 'Prism'' 'SomeException'  ()+-- @+_StackOverflow :: AsAsyncException t => Prism' t ()+_StackOverflow = _AsyncException . dimap seta (either id id) . right' . rmap (StackOverflow <$) where+  seta StackOverflow = Right ()+  seta t             = Left  (pure t)+{-# INLINE _StackOverflow #-}++pattern StackOverflow_ :: AsAsyncException s => s+pattern StackOverflow_ <- (has _StackOverflow -> True) where+  StackOverflow_ = review _StackOverflow ()++-- | The program's heap is reaching its limit, and the program should take action+-- to reduce the amount of live data it has.+--+-- Notes:+--+-- * It is undefined which thread receives this t'Exception'.+--+-- * GHC currently does not throw 'HeapOverflow' exceptions.+--+-- @+-- '_HeapOverflow' :: 'Prism'' 'AsyncException' ()+-- '_HeapOverflow' :: 'Prism'' 'SomeException'  ()+-- @+_HeapOverflow :: AsAsyncException t => Prism' t ()+_HeapOverflow = _AsyncException . dimap seta (either id id) . right' . rmap (HeapOverflow <$) where+  seta HeapOverflow = Right ()+  seta t            = Left  (pure t)+{-# INLINE _HeapOverflow #-}++pattern HeapOverflow_ :: AsAsyncException s => s+pattern HeapOverflow_ <- (has _HeapOverflow -> True) where+  HeapOverflow_ = review _HeapOverflow ()++-- | This t'Exception' is raised by another thread calling+-- 'Control.Concurrent.killThread', or by the system if it needs to terminate+-- the thread for some reason.+--+-- @+-- '_ThreadKilled' :: 'Prism'' 'AsyncException' ()+-- '_ThreadKilled' :: 'Prism'' 'SomeException'  ()+-- @+_ThreadKilled :: AsAsyncException t => Prism' t ()+_ThreadKilled = _AsyncException . dimap seta (either id id) . right' . rmap (ThreadKilled <$) where+  seta ThreadKilled = Right ()+  seta t            = Left  (pure t)+{-# INLINE _ThreadKilled #-}++pattern ThreadKilled_ :: AsAsyncException s => s+pattern ThreadKilled_ <- (has _ThreadKilled -> True) where+  ThreadKilled_ = review _ThreadKilled ()++-- | This t'Exception' is raised by default in the main thread of the program when+-- the user requests to terminate the program via the usual mechanism(s)+-- (/e.g./ Control-C in the console).+--+-- @+-- '_UserInterrupt' :: 'Prism'' 'AsyncException' ()+-- '_UserInterrupt' :: 'Prism'' 'SomeException'  ()+-- @+_UserInterrupt :: AsAsyncException t => Prism' t ()+_UserInterrupt = _AsyncException . dimap seta (either id id) . right' . rmap (UserInterrupt <$) where+  seta UserInterrupt = Right ()+  seta t             = Left  (pure t)+{-# INLINE _UserInterrupt #-}++pattern UserInterrupt_ :: AsAsyncException s => s+pattern UserInterrupt_ <- (has _UserInterrupt -> True) where+  UserInterrupt_ = review _UserInterrupt ()++----------------------------------------------------------------------------+-- AsyncException+----------------------------------------------------------------------------++-- | Thrown when the runtime system detects that the computation is guaranteed+-- not to terminate. Note that there is no guarantee that the runtime system+-- will notice whether any given computation is guaranteed to terminate or not.+class AsNonTermination t where+  -- |+  -- @+  -- '__NonTermination' :: 'Prism'' 'NonTermination' 'NonTermination'+  -- '__NonTermination' :: 'Prism'' 'SomeException'  'NonTermination'+  -- @+  __NonTermination :: Prism' t NonTermination++  -- | There is no additional information carried in a 'NonTermination' t'Exception'.+  --+  -- @+  -- '_NonTermination' :: 'Prism'' 'NonTermination' ()+  -- '_NonTermination' :: 'Prism'' 'SomeException'  ()+  -- @+  _NonTermination :: Prism' t ()+  _NonTermination = __NonTermination._NonTermination+  {-# INLINE _NonTermination #-}++instance AsNonTermination NonTermination where+  __NonTermination = id+  {-# INLINE __NonTermination #-}++  _NonTermination = trivial NonTermination+  {-# INLINE _NonTermination #-}++instance AsNonTermination SomeException where+  __NonTermination = exception+  {-# INLINE __NonTermination #-}++pattern NonTermination__ :: AsNonTermination s => NonTermination -> s+pattern NonTermination__ e <- (preview __NonTermination -> Just e) where+  NonTermination__ e = review __NonTermination e++pattern NonTermination_ :: AsNonTermination s => s+pattern NonTermination_ <- (has _NonTermination -> True) where+  NonTermination_ = review _NonTermination ()++----------------------------------------------------------------------------+-- NestedAtomically+----------------------------------------------------------------------------++-- | Thrown when the program attempts to call atomically, from the+-- 'Control.Monad.STM' package, inside another call to atomically.+class AsNestedAtomically t where+  -- |+  -- @+  -- '__NestedAtomically' :: 'Prism'' 'NestedAtomically' 'NestedAtomically'+  -- '__NestedAtomically' :: 'Prism'' 'SomeException'    'NestedAtomically'+  -- @+  __NestedAtomically :: Prism' t NestedAtomically++  -- | There is no additional information carried in a 'NestedAtomically' t'Exception'.+  --+  -- @+  -- '_NestedAtomically' :: 'Prism'' 'NestedAtomically' ()+  -- '_NestedAtomically' :: 'Prism'' 'SomeException'    ()+  -- @+  _NestedAtomically :: Prism' t ()+  _NestedAtomically = __NestedAtomically._NestedAtomically+  {-# INLINE _NestedAtomically #-}++instance AsNestedAtomically NestedAtomically where+  __NestedAtomically = id+  {-# INLINE __NestedAtomically #-}++  _NestedAtomically = trivial NestedAtomically+  {-# INLINE _NestedAtomically #-}++instance AsNestedAtomically SomeException where+  __NestedAtomically = exception+  {-# INLINE __NestedAtomically #-}++pattern NestedAtomically__ :: AsNestedAtomically s => NestedAtomically -> s+pattern NestedAtomically__ e <- (preview __NestedAtomically -> Just e) where+  NestedAtomically__ e = review __NestedAtomically e++pattern NestedAtomically_ :: AsNestedAtomically s => s+pattern NestedAtomically_ <- (has _NestedAtomically -> True) where+  NestedAtomically_ = review _NestedAtomically ()++----------------------------------------------------------------------------+-- BlockedIndefinitelyOnMVar+----------------------------------------------------------------------------++-- | The thread is blocked on an 'Control.Concurrent.MVar.MVar', but there+-- are no other references to the 'Control.Concurrent.MVar.MVar' so it can't+-- ever continue.+class AsBlockedIndefinitelyOnMVar t where+  -- |+  -- @+  -- '__BlockedIndefinitelyOnMVar' :: 'Prism'' 'BlockedIndefinitelyOnMVar' 'BlockedIndefinitelyOnMVar'+  -- '__BlockedIndefinitelyOnMVar' :: 'Prism'' 'SomeException'             'BlockedIndefinitelyOnMVar'+  -- @+  __BlockedIndefinitelyOnMVar :: Prism' t BlockedIndefinitelyOnMVar++  -- | There is no additional information carried in a 'BlockedIndefinitelyOnMVar' t'Exception'.+  --+  -- @+  -- '_BlockedIndefinitelyOnMVar' :: 'Prism'' 'BlockedIndefinitelyOnMVar' ()+  -- '_BlockedIndefinitelyOnMVar' :: 'Prism'' 'SomeException'             ()+  -- @+  _BlockedIndefinitelyOnMVar :: Prism' t ()+  _BlockedIndefinitelyOnMVar = __BlockedIndefinitelyOnMVar._BlockedIndefinitelyOnMVar+  {-# INLINE _BlockedIndefinitelyOnMVar #-}++instance AsBlockedIndefinitelyOnMVar BlockedIndefinitelyOnMVar where+  __BlockedIndefinitelyOnMVar = id+  {-# INLINE __BlockedIndefinitelyOnMVar #-}++  _BlockedIndefinitelyOnMVar = trivial BlockedIndefinitelyOnMVar+  {-# INLINE _BlockedIndefinitelyOnMVar #-}++instance AsBlockedIndefinitelyOnMVar SomeException where+  __BlockedIndefinitelyOnMVar = exception+  {-# INLINE __BlockedIndefinitelyOnMVar #-}++pattern BlockedIndefinitelyOnMVar__ :: AsBlockedIndefinitelyOnMVar s => BlockedIndefinitelyOnMVar -> s+pattern BlockedIndefinitelyOnMVar__ e <- (preview __BlockedIndefinitelyOnMVar -> Just e) where+  BlockedIndefinitelyOnMVar__ e = review __BlockedIndefinitelyOnMVar e++pattern BlockedIndefinitelyOnMVar_ :: AsBlockedIndefinitelyOnMVar s => s+pattern BlockedIndefinitelyOnMVar_ <- (has _BlockedIndefinitelyOnMVar -> True) where+  BlockedIndefinitelyOnMVar_ = review _BlockedIndefinitelyOnMVar ()++----------------------------------------------------------------------------+-- BlockedIndefinitelyOnSTM+----------------------------------------------------------------------------++-- | The thread is waiting to retry an 'Control.Monad.STM.STM' transaction,+-- but there are no other references to any TVars involved, so it can't ever+-- continue.+class AsBlockedIndefinitelyOnSTM t where+  -- |+  -- @+  -- '__BlockedIndefinitelyOnSTM' :: 'Prism'' 'BlockedIndefinitelyOnSTM' 'BlockedIndefinitelyOnSTM'+  -- '__BlockedIndefinitelyOnSTM' :: 'Prism'' 'SomeException'            'BlockedIndefinitelyOnSTM'+  -- @+  __BlockedIndefinitelyOnSTM :: Prism' t BlockedIndefinitelyOnSTM++  -- | There is no additional information carried in a 'BlockedIndefinitelyOnSTM' t'Exception'.+  --+  -- @+  -- '_BlockedIndefinitelyOnSTM' :: 'Prism'' 'BlockedIndefinitelyOnSTM' ()+  -- '_BlockedIndefinitelyOnSTM' :: 'Prism'' 'SomeException'            ()+  -- @+  _BlockedIndefinitelyOnSTM :: Prism' t ()+  _BlockedIndefinitelyOnSTM = __BlockedIndefinitelyOnSTM._BlockedIndefinitelyOnSTM+  {-# INLINE _BlockedIndefinitelyOnSTM #-}++instance AsBlockedIndefinitelyOnSTM BlockedIndefinitelyOnSTM where+  __BlockedIndefinitelyOnSTM = id+  {-# INLINE __BlockedIndefinitelyOnSTM #-}++  _BlockedIndefinitelyOnSTM = trivial BlockedIndefinitelyOnSTM+  {-# INLINE _BlockedIndefinitelyOnSTM #-}++instance AsBlockedIndefinitelyOnSTM SomeException where+  __BlockedIndefinitelyOnSTM = exception+  {-# INLINE __BlockedIndefinitelyOnSTM #-}++pattern BlockedIndefinitelyOnSTM__ :: AsBlockedIndefinitelyOnSTM s => BlockedIndefinitelyOnSTM -> s+pattern BlockedIndefinitelyOnSTM__ e <- (preview __BlockedIndefinitelyOnSTM -> Just e) where+  BlockedIndefinitelyOnSTM__ e = review __BlockedIndefinitelyOnSTM e++pattern BlockedIndefinitelyOnSTM_ :: AsBlockedIndefinitelyOnSTM s => s+pattern BlockedIndefinitelyOnSTM_ <- (has _BlockedIndefinitelyOnSTM -> True) where+  BlockedIndefinitelyOnSTM_ = review _BlockedIndefinitelyOnSTM ()++----------------------------------------------------------------------------+-- Deadlock+----------------------------------------------------------------------------++-- | There are no runnable threads, so the program is deadlocked. The+-- 'Deadlock' t'Exception' is raised in the main thread only.+class AsDeadlock t where+  -- |+  -- @+  -- '__Deadlock' :: 'Prism'' 'Deadlock'      'Deadlock'+  -- '__Deadlock' :: 'Prism'' 'SomeException' 'Deadlock'+  -- @+  __Deadlock :: Prism' t Deadlock++  -- | There is no information carried in a 'Deadlock' t'Exception'.+  --+  -- @+  -- '_Deadlock' :: 'Prism'' 'Deadlock'      ()+  -- '_Deadlock' :: 'Prism'' 'SomeException' ()+  -- @+  _Deadlock :: Prism' t ()+  _Deadlock = __Deadlock._Deadlock+  {-# INLINE _Deadlock #-}++instance AsDeadlock Deadlock where+  __Deadlock = id+  {-# INLINE __Deadlock #-}++  _Deadlock = trivial Deadlock+  {-# INLINE _Deadlock #-}++instance AsDeadlock SomeException where+  __Deadlock = exception+  {-# INLINE __Deadlock #-}++pattern Deadlock__ :: AsDeadlock s => Deadlock -> s+pattern Deadlock__ e <- (preview __Deadlock -> Just e) where+  Deadlock__ e = review __Deadlock e++pattern Deadlock_ :: AsDeadlock s => s+pattern Deadlock_ <- (has _Deadlock -> True) where+  Deadlock_ = review _Deadlock ()++----------------------------------------------------------------------------+-- NoMethodError+----------------------------------------------------------------------------++-- | A class method without a definition (neither a default definition,+-- nor a definition in the appropriate instance) was called.+class AsNoMethodError t where+  -- |+  -- @+  -- '__NoMethodError' :: 'Prism'' 'NoMethodError' 'NoMethodError'+  -- '__NoMethodError' :: 'Prism'' 'SomeException' 'NoMethodError'+  -- @+  __NoMethodError :: Prism' t NoMethodError++  -- | Extract a description of the missing method.+  --+  -- @+  -- '_NoMethodError' :: 'Prism'' 'NoMethodError' 'String'+  -- '_NoMethodError' :: 'Prism'' 'SomeException' 'String'+  -- @+  _NoMethodError :: Prism' t String+  _NoMethodError = __NoMethodError._NoMethodError+  {-# INLINE _NoMethodError #-}++instance AsNoMethodError NoMethodError where+  __NoMethodError = id+  {-# INLINE __NoMethodError #-}++  _NoMethodError = _Wrapping NoMethodError+  {-# INLINE _NoMethodError #-}++instance AsNoMethodError SomeException where+  __NoMethodError = exception+  {-# INLINE __NoMethodError #-}++pattern NoMethodError__ :: AsNoMethodError s => NoMethodError -> s+pattern NoMethodError__ e <- (preview __NoMethodError -> Just e) where+  NoMethodError__ e = review __NoMethodError e++pattern NoMethodError_ :: AsNoMethodError s => String -> s+pattern NoMethodError_ e <- (preview _NoMethodError -> Just e) where+  NoMethodError_ e = review _NoMethodError e++----------------------------------------------------------------------------+-- PatternMatchFail+----------------------------------------------------------------------------++-- | A pattern match failed.+class AsPatternMatchFail t where+  -- |+  -- @+  -- '__PatternMatchFail' :: 'Prism'' 'PatternMatchFail' 'PatternMatchFail'+  -- '__PatternMatchFail' :: 'Prism'' 'SomeException'    'PatternMatchFail'+  -- @+  __PatternMatchFail :: Prism' t PatternMatchFail++  -- | Information about the source location of the pattern.+  --+  -- @+  -- '_PatternMatchFail' :: 'Prism'' 'PatternMatchFail' 'String'+  -- '_PatternMatchFail' :: 'Prism'' 'SomeException'    'String'+  -- @+  _PatternMatchFail :: Prism' t String+  _PatternMatchFail = __PatternMatchFail._PatternMatchFail+  {-# INLINE _PatternMatchFail #-}++instance AsPatternMatchFail PatternMatchFail where+  __PatternMatchFail = id+  {-# INLINE __PatternMatchFail #-}++  _PatternMatchFail = _Wrapping PatternMatchFail+  {-# INLINE _PatternMatchFail #-}++instance AsPatternMatchFail SomeException where+  __PatternMatchFail = exception+  {-# INLINE __PatternMatchFail #-}++pattern PatternMatchFail__ :: AsPatternMatchFail s => PatternMatchFail -> s+pattern PatternMatchFail__ e <- (preview __PatternMatchFail -> Just e) where+  PatternMatchFail__ e = review __PatternMatchFail e++pattern PatternMatchFail_ :: AsPatternMatchFail s => String -> s+pattern PatternMatchFail_ e <- (preview _PatternMatchFail -> Just e) where+  PatternMatchFail_ e = review _PatternMatchFail e++----------------------------------------------------------------------------+-- RecConError+----------------------------------------------------------------------------++-- | An uninitialised record field was used.+class AsRecConError t where+  -- |+  -- @+  -- '__RecConError' :: 'Prism'' 'RecConError'   'RecConError'+  -- '__RecConError' :: 'Prism'' 'SomeException' 'RecConError'+  -- @+  __RecConError :: Prism' t RecConError++  -- | Information about the source location where the record was+  -- constructed.+  --+  -- @+  -- '_RecConError' :: 'Prism'' 'RecConError'   'String'+  -- '_RecConError' :: 'Prism'' 'SomeException' 'String'+  -- @+  _RecConError :: Prism' t String+  _RecConError = __RecConError._RecConError+  {-# INLINE _RecConError #-}++instance AsRecConError RecConError where+  __RecConError = id+  {-# INLINE __RecConError #-}++  _RecConError = _Wrapping RecConError+  {-# INLINE _RecConError #-}++instance AsRecConError SomeException where+  __RecConError = exception+  {-# INLINE __RecConError #-}++pattern RecConError__ :: AsRecConError s => RecConError -> s+pattern RecConError__ e <- (preview __RecConError -> Just e) where+  RecConError__ e = review __RecConError e++pattern RecConError_ :: AsRecConError s => String -> s+pattern RecConError_ e <- (preview _RecConError -> Just e) where+  RecConError_ e = review _RecConError e++----------------------------------------------------------------------------+-- RecSelError+----------------------------------------------------------------------------++-- | A record selector was applied to a constructor without the appropriate+-- field. This can only happen with a datatype with multiple constructors,+-- where some fields are in one constructor but not another.+class AsRecSelError t where+  -- |+  -- @+  -- '__RecSelError' :: 'Prism'' 'RecSelError'   'RecSelError'+  -- '__RecSelError' :: 'Prism'' 'SomeException' 'RecSelError'+  -- @+  __RecSelError :: Prism' t RecSelError++  -- | Information about the source location where the record selection occurred.+  --+  -- @+  -- '_RecSelError' :: 'Prism'' 'RecSelError'   'String'+  -- '_RecSelError' :: 'Prism'' 'SomeException' 'String'+  -- @+  _RecSelError :: Prism' t String+  _RecSelError = __RecSelError._RecSelError+  {-# INLINE _RecSelError #-}++instance AsRecSelError RecSelError where+  __RecSelError = id+  {-# INLINE __RecSelError #-}++  _RecSelError = _Wrapping RecSelError+  {-# INLINE _RecSelError #-}++instance AsRecSelError SomeException where+  __RecSelError = exception+  {-# INLINE __RecSelError #-}++pattern RecSelError__ :: AsRecSelError s => RecSelError -> s+pattern RecSelError__ e <- (preview __RecSelError -> Just e) where+  RecSelError__ e = review __RecSelError e++pattern RecSelError_ :: AsRecSelError s => String -> s+pattern RecSelError_ e <- (preview _RecSelError -> Just e) where+  RecSelError_ e = review _RecSelError e++----------------------------------------------------------------------------+-- RecUpdError+----------------------------------------------------------------------------++-- | A record update was performed on a constructor without the+-- appropriate field. This can only happen with a datatype with multiple+-- constructors, where some fields are in one constructor but not another.+class AsRecUpdError t where+  -- |+  -- @+  -- '__RecUpdError' :: 'Prism'' 'RecUpdError'   'RecUpdError'+  -- '__RecUpdError' :: 'Prism'' 'SomeException' 'RecUpdError'+  -- @+  __RecUpdError :: Prism' t RecUpdError++  -- | Information about the source location where the record was updated.+  --+  -- @+  -- '_RecUpdError' :: 'Prism'' 'RecUpdError'   'String'+  -- '_RecUpdError' :: 'Prism'' 'SomeException' 'String'+  -- @+  _RecUpdError :: Prism' t String+  _RecUpdError = __RecUpdError._RecUpdError+  {-# INLINE _RecUpdError #-}++instance AsRecUpdError RecUpdError where+  __RecUpdError = id+  {-# INLINE __RecUpdError #-}++  _RecUpdError = _Wrapping RecUpdError+  {-# INLINE _RecUpdError #-}++instance AsRecUpdError SomeException where+  __RecUpdError = exception+  {-# INLINE __RecUpdError #-}++pattern RecUpdError__ :: AsRecUpdError s => RecUpdError -> s+pattern RecUpdError__ e <- (preview __RecUpdError -> Just e) where+  RecUpdError__ e = review __RecUpdError e++pattern RecUpdError_ :: AsRecUpdError s => String -> s+pattern RecUpdError_ e <- (preview _RecUpdError -> Just e) where+  RecUpdError_ e = review _RecUpdError e++----------------------------------------------------------------------------+-- ErrorCall+----------------------------------------------------------------------------++-- | This is thrown when the user calls 'Prelude.error'.+class AsErrorCall t where+  -- |+  -- @+  -- '__ErrorCall' :: 'Prism'' 'ErrorCall'     'ErrorCall'+  -- '__ErrorCall' :: 'Prism'' 'SomeException' 'ErrorCall'+  -- @+  __ErrorCall :: Prism' t ErrorCall++  -- | Retrieve the argument given to 'Prelude.error'.+  --+  -- 'ErrorCall' is isomorphic to a 'String'.+  --+  -- >>> catching _ErrorCall (error "touch down!") return+  -- "touch down!"+  --+  -- @+  -- '_ErrorCall' :: 'Prism'' 'ErrorCall'     'String'+  -- '_ErrorCall' :: 'Prism'' 'SomeException' 'String'+  -- @+  _ErrorCall :: Prism' t String+  _ErrorCall = __ErrorCall._ErrorCall+  {-# INLINE _ErrorCall #-}++instance AsErrorCall ErrorCall where+  __ErrorCall = id+  {-# INLINE __ErrorCall #-}++  _ErrorCall = _Wrapping ErrorCall+  {-# INLINE _ErrorCall #-}++instance AsErrorCall SomeException where+  __ErrorCall = exception+  {-# INLINE __ErrorCall #-}++pattern ErrorCall__ :: AsErrorCall s => ErrorCall -> s+pattern ErrorCall__ e <- (preview __ErrorCall -> Just e) where+  ErrorCall__ e = review __ErrorCall e++pattern ErrorCall_ :: AsErrorCall s => String -> s+pattern ErrorCall_ e <- (preview _ErrorCall -> Just e) where+  ErrorCall_ e = review _ErrorCall e++----------------------------------------------------------------------------+-- AllocationLimitExceeded+----------------------------------------------------------------------------++-- | This thread has exceeded its allocation limit.+class AsAllocationLimitExceeded t where+  -- |+  -- @+  -- '__AllocationLimitExceeded' :: 'Prism'' 'AllocationLimitExceeded' 'AllocationLimitExceeded'+  -- '__AllocationLimitExceeded' :: 'Prism'' 'SomeException'           'AllocationLimitExceeded'+  -- @+  __AllocationLimitExceeded :: Prism' t AllocationLimitExceeded++  -- | There is no additional information carried in an+  -- 'AllocationLimitExceeded' t'Exception'.+  --+  -- @+  -- '_AllocationLimitExceeded' :: 'Prism'' 'AllocationLimitExceeded' ()+  -- '_AllocationLimitExceeded' :: 'Prism'' 'SomeException'           ()+  -- @+  _AllocationLimitExceeded :: Prism' t ()+  _AllocationLimitExceeded = __AllocationLimitExceeded._AllocationLimitExceeded+  {-# INLINE _AllocationLimitExceeded #-}++instance AsAllocationLimitExceeded AllocationLimitExceeded where+  __AllocationLimitExceeded = id+  {-# INLINE __AllocationLimitExceeded #-}++  _AllocationLimitExceeded = trivial AllocationLimitExceeded+  {-# INLINE _AllocationLimitExceeded #-}++instance AsAllocationLimitExceeded SomeException where+  __AllocationLimitExceeded = exception+  {-# INLINE __AllocationLimitExceeded #-}++pattern AllocationLimitExceeded__ :: AsAllocationLimitExceeded s => AllocationLimitExceeded -> s+pattern AllocationLimitExceeded__ e <- (preview __AllocationLimitExceeded -> Just e) where+  AllocationLimitExceeded__ e = review __AllocationLimitExceeded e++pattern AllocationLimitExceeded_ :: AsAllocationLimitExceeded s => s+pattern AllocationLimitExceeded_ <- (has _AllocationLimitExceeded -> True) where+  AllocationLimitExceeded_ = review _AllocationLimitExceeded ()++----------------------------------------------------------------------------+-- TypeError+----------------------------------------------------------------------------++-- | An expression that didn't typecheck during compile time was called.+-- This is only possible with @-fdefer-type-errors@.+class AsTypeError t where+  -- |+  -- @+  -- '__TypeError' :: 'Prism'' 'TypeError'     'TypeError'+  -- '__TypeError' :: 'Prism'' 'SomeException' 'TypeError'+  -- @+  __TypeError :: Prism' t TypeError++  -- | Details about the failed type check.+  --+  -- @+  -- '_TypeError' :: 'Prism'' 'TypeError'     'String'+  -- '_TypeError' :: 'Prism'' 'SomeException' 'String'+  -- @+  _TypeError :: Prism' t String+  _TypeError = __TypeError._TypeError+  {-# INLINE _TypeError #-}++instance AsTypeError TypeError where+  __TypeError = id+  {-# INLINE __TypeError #-}++  _TypeError = _Wrapping TypeError+  {-# INLINE _TypeError #-}++instance AsTypeError SomeException where+  __TypeError = exception+  {-# INLINE __TypeError #-}++pattern TypeError__ :: AsTypeError s => TypeError -> s+pattern TypeError__ e <- (preview __TypeError -> Just e) where+  TypeError__ e = review __TypeError e++pattern TypeError_ :: AsTypeError s => String -> s+pattern TypeError_ e <- (preview _TypeError -> Just e) where+  TypeError_ e = review _TypeError e++#if MIN_VERSION_base(4,10,0)+----------------------------------------------------------------------------+-- CompactionFailed+----------------------------------------------------------------------------++-- | Compaction found an object that cannot be compacted.+-- Functions cannot be compacted, nor can mutable objects or pinned objects.+class AsCompactionFailed t where+  -- |+  -- @+  -- '__CompactionFailed' :: 'Prism'' 'CompactionFailed' 'CompactionFailed'+  -- '__CompactionFailed' :: 'Prism'' 'SomeException'    'CompactionFailed'+  -- @+  __CompactionFailed :: Prism' t CompactionFailed++  -- | Information about why a compaction failed.+  --+  -- @+  -- '_CompactionFailed' :: 'Prism'' 'CompactionFailed' 'String'+  -- '_CompactionFailed' :: 'Prism'' 'SomeException'    'String'+  -- @+  _CompactionFailed :: Prism' t String+  _CompactionFailed = __CompactionFailed._CompactionFailed+  {-# INLINE _CompactionFailed #-}++instance AsCompactionFailed CompactionFailed where+  __CompactionFailed = id+  {-# INLINE __CompactionFailed #-}++  _CompactionFailed = _Wrapping CompactionFailed+  {-# INLINE _CompactionFailed #-}++instance AsCompactionFailed SomeException where+  __CompactionFailed = exception+  {-# INLINE __CompactionFailed #-}++pattern CompactionFailed__ :: AsCompactionFailed s => CompactionFailed -> s+pattern CompactionFailed__ e <- (preview __CompactionFailed -> Just e) where+  CompactionFailed__ e = review __CompactionFailed e++pattern CompactionFailed_ :: AsCompactionFailed s => String -> s+pattern CompactionFailed_ e <- (preview _CompactionFailed -> Just e) where+  CompactionFailed_ e = review _CompactionFailed e+#endif++------------------------------------------------------------------------------+-- HandlingException+------------------------------------------------------------------------------++-- | This t'Exception' is thrown by @lens@ when the user somehow manages to rethrow+-- an internal 'HandlingException'.+class AsHandlingException t where+  -- |+  -- @+  -- '__HandlingException' :: 'Prism'' 'HandlingException' 'HandlingException'+  -- '__HandlingException' :: 'Prism'' 'SomeException'     'HandlingException'+  -- @+  __HandlingException :: Prism' t HandlingException++  -- | There is no information carried in a 'HandlingException'.+  --+  -- @+  -- '_HandlingException' :: 'Prism'' 'HandlingException' ()+  -- '_HandlingException' :: 'Prism'' 'SomeException'     ()+  -- @+  _HandlingException :: Prism' t ()+  _HandlingException = __HandlingException._HandlingException+  {-# INLINE _HandlingException #-}++instance AsHandlingException HandlingException where+  __HandlingException = id+  {-# INLINE __HandlingException #-}++  _HandlingException = trivial HandlingException+  {-# INLINE _HandlingException #-}++instance AsHandlingException SomeException where+  __HandlingException = exception+  {-# INLINE __HandlingException #-}++pattern HandlingException__ :: AsHandlingException s => HandlingException -> s+pattern HandlingException__ e <- (preview __HandlingException -> Just e) where+  HandlingException__ e = review __HandlingException e++pattern HandlingException_ :: AsHandlingException s => s+pattern HandlingException_ <- (has _HandlingException -> True) where+  HandlingException_ = review _HandlingException ()++------------------------------------------------------------------------------+-- Helper Functions+------------------------------------------------------------------------------++trivial :: t -> Iso' t ()+trivial t = const () `iso` const t
src/Control/Lens.hs view
@@ -1,16 +1,12 @@ {-# LANGUAGE CPP #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE Rank2Types #-}-{-# LANGUAGE LiberalTypeSynonyms #-}-{-# LANGUAGE FlexibleContexts #-} ----------------------------------------------------------------------------- -- | -- Module      :  Control.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  Rank2Types+-- Stability   :  experimental+-- Portability :  non-portable -- -- Usage: --@@ -18,20 +14,24 @@ -- -- @ -- import Control.Lens--- data Foo a = Foo { _fooArgs :: ['String'], _fooValue :: a }--- 'makeLenses' ''Foo+--+-- data FooBar a+--   = Foo { _x :: ['Int'], _y :: a }+--   | Bar { _x :: ['Int'] }+-- 'makeLenses' ''FooBar -- @ -- -- This defines the following lenses: -- -- @--- fooArgs :: 'Simple' 'Lens' (Foo a) ['String']--- fooValue :: 'Lens' (Foo a) (Foo b) a b+-- x :: 'Lens'' (FooBar a) ['Int']+-- y :: t'Traversal' (FooBar a) (FooBar b) a b -- @ ----- You can then access the value with ('^.') and set the value of the field--- with ('.~') and can use almost any other combinator that is re-exported--- here on those fields.+-- You can then access the value of @_x@ with ('^.'), the value of @_y@ –+-- with ('^?') or ('^?!') (since it can fail), set the values with ('.~'),+-- modify them with ('%~'), and use almost any other combinator that is+-- re-exported here on those fields. -- -- The combinators here have unusually specific type signatures, so for -- particularly tricky ones, the simpler type signatures you might want to@@ -41,48 +41,50 @@ -- -- <http://github.com/ekmett/lens/wiki> ----- <<http://github.com/ekmett/lens/wiki/images/Hierarchy-2.9.png>>+-- <<Hierarchy.png>> ---------------------------------------------------------------------------- module Control.Lens-  ( module Control.Lens.Type-  , module Control.Lens.Traversal-  , module Control.Lens.Getter-  , module Control.Lens.Setter-  , module Control.Lens.Action-  , module Control.Lens.Combinators+  ( module Control.Lens.At+  , module Control.Lens.Cons+  , module Control.Lens.Each+  , module Control.Lens.Empty+  , module Control.Lens.Equality   , module Control.Lens.Fold-  , module Control.Lens.Iso+  , module Control.Lens.Getter   , module Control.Lens.Indexed-  , module Control.Lens.IndexedFold-  , module Control.Lens.IndexedGetter-  , module Control.Lens.IndexedLens-  , module Control.Lens.IndexedTraversal-  , module Control.Lens.IndexedSetter+  , module Control.Lens.Iso+  , module Control.Lens.Lens+  , module Control.Lens.Level   , module Control.Lens.Plated-  , module Control.Lens.Projection-  , module Control.Lens.Representable+  , module Control.Lens.Prism+  , module Control.Lens.Reified+  , module Control.Lens.Review+  , module Control.Lens.Setter #ifndef DISABLE_TEMPLATE_HASKELL   , module Control.Lens.TH #endif+  , module Control.Lens.Traversal   , module Control.Lens.Tuple-  , module Control.Lens.WithIndex+  , module Control.Lens.Type+  , module Control.Lens.Wrapped   , module Control.Lens.Zoom   ) where -import Control.Lens.Action-import Control.Lens.Combinators+import Control.Lens.At+import Control.Lens.Cons+import Control.Lens.Each+import Control.Lens.Empty+import Control.Lens.Equality import Control.Lens.Fold import Control.Lens.Getter import Control.Lens.Indexed-import Control.Lens.IndexedFold-import Control.Lens.IndexedGetter-import Control.Lens.IndexedLens-import Control.Lens.IndexedSetter-import Control.Lens.IndexedTraversal import Control.Lens.Iso+import Control.Lens.Lens+import Control.Lens.Level import Control.Lens.Plated-import Control.Lens.Projection-import Control.Lens.Representable+import Control.Lens.Prism+import Control.Lens.Reified+import Control.Lens.Review import Control.Lens.Setter #ifndef DISABLE_TEMPLATE_HASKELL import Control.Lens.TH@@ -90,5 +92,5 @@ import Control.Lens.Traversal import Control.Lens.Tuple import Control.Lens.Type-import Control.Lens.WithIndex+import Control.Lens.Wrapped import Control.Lens.Zoom
− src/Control/Lens/Action.hs
@@ -1,95 +0,0 @@-{-# LANGUAGE Rank2Types #-}-{-# LANGUAGE MultiParamTypeClasses #-}--------------------------------------------------------------------------------- |--- Module      :  Control.Lens.Action--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  experimental--- Portability :  MTPCs, FDs, Rank2---------------------------------------------------------------------------------module Control.Lens.Action-  (-  -- * Composable Actions-    Action-  , act-  , acts-  , perform-  , performs-  , liftAct-  , (^!)--  -- * Folds with Effecs-  , MonadicFold--  -- * Implementation Details-  , Acting-  ) where--import Control.Applicative-import Control.Lens.Internal-import Control.Monad.Trans.Class---- $setup--- >>> import Control.Lens--infixr 8 ^!---- | An 'Action' is a 'Getter' enriched with access to a 'Monad' for side-effects.------ Every 'Getter' can be used as an 'Action'------ You can compose an 'Action' with another 'Action' using ('Prelude..') from the @Prelude@.-type Action m a c = forall f r. Effective m r f => (c -> f c) -> a -> f a---- | A 'MonadicFold' is a 'Fold' enriched with access to a 'Monad' for side-effects.------ Every 'Fold' can be used as a 'MonadicFold', that simply ignores the access to the 'Monad'.------ You can compose a 'MonadicFold' with another 'MonadicFold' using ('Prelude..') from the @Prelude@.-type MonadicFold m a c = forall f r. (Effective m r f, Applicative f) => (c -> f c) -> a -> f a---- | Used to evaluate an 'Action'.-type Acting m r a b c d = (c -> Effect m r d) -> a -> Effect m r b---- | Perform an 'Action'.------ > perform = flip (^!)-perform :: Monad m => Acting m c a b c d -> a -> m c-perform l = getEffect . l (Effect . return)-{-# INLINE perform #-}---- | Perform an 'Action' and modify the result.-performs :: Monad m => Acting m e a b c d -> (c -> e) -> a -> m e-performs l f = getEffect . l (Effect . return . f)---- | Perform an 'Action'------ >>> ["hello","world"]^!folded.act putStrLn--- hello--- world-(^!) :: Monad m => a -> Acting m c a b c d -> m c-a ^! l = getEffect (l (Effect . return) a)-{-# INLINE (^!) #-}---- | Construct an 'Action' from a monadic side-effect-act :: Monad m => (a -> m c) -> Action m a c-act amc cfd a = effective (amc a >>= ineffective . cfd)-{-# INLINE act #-}---- | A self-running 'Action', analogous to 'Control.Monad.join'.------ @'acts' = 'act' 'id'@------ >>> (1,"hello")^!_2.acts.to succ--- "ifmmp"-acts :: Action m (m a) a-acts = act id-{-# INLINE acts #-}---- | Apply a 'Monad' transformer to an 'Action'.-liftAct :: (MonadTrans t, Monad m) => Acting m c a b c d -> Action (t m) a c-liftAct l = act (lift . perform l)-{-# INLINE liftAct #-}
+ src/Control/Lens/At.hs view
@@ -0,0 +1,604 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE DefaultSignatures #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE TypeOperators #-}++#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-}+#endif++#include "lens-common.h"++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.At+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+----------------------------------------------------------------------------+module Control.Lens.At+  (+  -- * At+    At(at)+    , sans+    , iat+  -- * Ixed+  , Index+  , IxValue+  , Ixed(ix)+  , ixAt+  , iix+  -- * Contains+  , Contains(contains)+  , icontains+  ) where++import Prelude ()++import Control.Lens.Each+import Control.Lens.Internal.Prelude+import Control.Lens.Traversal+import Control.Lens.Lens+import Control.Lens.Setter+import Control.Lens.Indexed+import Control.Monad (guard)+import Data.Array.IArray as Array+import Data.Array.Unboxed+import qualified Data.ByteString as StrictB+import qualified Data.ByteString.Lazy as LazyB+import Data.Complex+import Data.Functor (($>))+import Data.Hashable+import qualified Data.HashMap.Lazy as HashMap+import Data.HashMap.Lazy (HashMap)+import qualified Data.HashSet as HashSet+import Data.HashSet (HashSet)+import Data.Int+import qualified Data.IntMap as IntMap+import Data.IntMap (IntMap)+import qualified Data.IntSet as IntSet+import Data.IntSet (IntSet)+import Data.Kind+import qualified Data.Map as Map+import Data.Map (Map)+import Data.Maybe (isJust)+import qualified Data.Set as Set+import Data.Set (Set)+import qualified Data.Sequence as Seq+import Data.Sequence (Seq)+import qualified Data.Text as StrictT+import qualified Data.Text.Lazy as LazyT+import Data.Tree+import qualified Data.Vector as Vector+import qualified Data.Vector.Primitive as Prim+import Data.Vector.Primitive (Prim)+import qualified Data.Vector.Storable as Storable+import qualified Data.Vector.Unboxed as Unboxed+import Data.Vector.Unboxed (Unbox)+#if MIN_VERSION_vector(0,13,2)+import qualified Data.Vector.Strict as VectorStrict+#endif+import Data.Word+import Foreign.Storable (Storable)++type family Index (s :: Type) :: Type+type instance Index (e -> a) = e+type instance Index IntSet = Int+type instance Index (Set a) = a+type instance Index (HashSet a) = a+type instance Index [a] = Int+type instance Index (NonEmpty a) = Int+type instance Index (Seq a) = Int+type instance Index (a,b) = Int+type instance Index (a,b,c) = Int+type instance Index (a,b,c,d) = Int+type instance Index (a,b,c,d,e) = Int+type instance Index (a,b,c,d,e,f) = Int+type instance Index (a,b,c,d,e,f,g) = Int+type instance Index (a,b,c,d,e,f,g,h) = Int+type instance Index (a,b,c,d,e,f,g,h,i) = Int+type instance Index (IntMap a) = Int+type instance Index (Map k a) = k+type instance Index (HashMap k a) = k+type instance Index (Array.Array i e) = i+type instance Index (UArray i e) = i+type instance Index (Vector.Vector a) = Int+type instance Index (Prim.Vector a) = Int+type instance Index (Storable.Vector a) = Int+type instance Index (Unboxed.Vector a) = Int+#if MIN_VERSION_vector(0,13,2)+type instance Index (VectorStrict.Vector a) = Int+#endif+type instance Index (Complex a) = Int+type instance Index (Identity a) = ()+type instance Index (Maybe a) = ()+type instance Index (Tree a) = [Int]+type instance Index StrictT.Text = Int+type instance Index LazyT.Text = Int64+type instance Index StrictB.ByteString = Int+type instance Index LazyB.ByteString = Int64++-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import qualified Data.IntSet as IntSet+-- >>> import qualified Data.Sequence as Seq+-- >>> import qualified Data.Map as Map+-- >>> import Debug.SimpleReflect.Expr+-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g)+-- >>> let f  :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f+-- >>> let g  :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g+-- >>> let f' :: Int -> Expr -> Expr; f' = Debug.SimpleReflect.Vars.f'+-- >>> let h  :: Int -> Expr; h = Debug.SimpleReflect.Vars.h++-- |+-- This class provides a simple 'Lens' that lets you view (and modify)+-- information about whether or not a container contains a given 'Index'.+class Contains m where+  -- |+  -- >>> IntSet.fromList [1,2,3,4] ^. contains 3+  -- True+  --+  -- >>> IntSet.fromList [1,2,3,4] ^. contains 5+  -- False+  --+  -- >>> IntSet.fromList [1,2,3,4] & contains 3 .~ False+  -- fromList [1,2,4]+  contains :: Index m -> Lens' m Bool++-- | An indexed version of 'contains'.+--+-- >>> IntSet.fromList [1,2,3,4] ^@. icontains 3+-- (3,True)+--+-- >>> IntSet.fromList [1,2,3,4] ^@. icontains 5+-- (5,False)+--+-- >>> IntSet.fromList [1,2,3,4] & icontains 3 %@~ \i x -> if odd i then not x else x+-- fromList [1,2,4]+--+-- >>> IntSet.fromList [1,2,3,4] & icontains 3 %@~ \i x -> if even i then not x else x+-- fromList [1,2,3,4]+icontains :: Contains m => Index m -> IndexedLens' (Index m) m Bool+icontains i f = contains i (indexed f i)+{-# INLINE icontains #-}++instance Contains IntSet where+#if MIN_VERSION_containers(0,6,3)+  contains k f = IntSet.alterF f k+#else+  -- This is a flipped copy of the implementation of `IntSet.alterF`.  Unlike a+  -- `Set`, we don't have to worry about expensive comparisons from descending+  -- multiple times into an `IntSet`. We are careful to share the results of+  -- insertion or deletion across multiple positions in the `Functor`.+  contains k f s = fmap choose (f member_)+    where+      member_ = IntSet.member k s++      (inserted, deleted)+        | member_   = (s, IntSet.delete k s)+        | otherwise = (IntSet.insert k s, s)++      choose True  = inserted+      choose False = deleted+#endif+  {-# INLINE contains #-}++instance Ord a => Contains (Set a) where+#if MIN_VERSION_containers(0,6,3)+  contains k f = Set.alterF f k+#else+  contains k f s = f (Set.member k s) <&> \b ->+    if b then Set.insert k s else Set.delete k s+#endif+  {-# INLINE contains #-}++instance (Eq a, Hashable a) => Contains (HashSet a) where+  contains k f s = HashSet.fromMap <$>+    HashMap.alterF (fmap guard . f . isJust) k (HashSet.toMap s)+  {-# INLINE contains #-}++-- | This provides a common notion of a value at an index that is shared by both 'Ixed' and 'At'.+type family IxValue (m :: Type) :: Type++-- | Provides a simple 'Traversal' lets you 'traverse' the value at a given+-- key in a 'Map' or element at an ordinal position in a list or 'Seq'.+class Ixed m where+  -- |+  -- /NB:/ Setting the value of this 'Traversal' will only set the value in+  -- 'at' if it is already present.+  --+  -- If you want to be able to insert /missing/ values, you want 'at'.+  --+  -- >>> Seq.fromList [a,b,c,d] & ix 2 %~ f+  -- fromList [a,b,f c,d]+  --+  -- >>> Seq.fromList [a,b,c,d] & ix 2 .~ e+  -- fromList [a,b,e,d]+  --+  -- >>> Seq.fromList [a,b,c,d] ^? ix 2+  -- Just c+  --+  -- >>> Seq.fromList [] ^? ix 2+  -- Nothing+  ix :: Index m -> Traversal' m (IxValue m)+  default ix :: At m => Index m -> Traversal' m (IxValue m)+  ix = ixAt+  {-# INLINE ix #-}++-- | An indexed version of 'ix'.+--+-- >>> Seq.fromList [a,b,c,d] & iix 2 %@~ f'+-- fromList [a,b,f' 2 c,d]+--+-- >>> Seq.fromList [a,b,c,d] & iix 2 .@~ h+-- fromList [a,b,h 2,d]+--+-- >>> Seq.fromList [a,b,c,d] ^@? iix 2+-- Just (2,c)+--+-- >>> Seq.fromList [] ^@? iix 2+-- Nothing+iix :: Ixed m => Index m -> IndexedTraversal' (Index m) m (IxValue m)+iix i f = ix i (indexed f i)+{-# INLINE iix #-}++-- | A definition of 'ix' for types with an 'At' instance. This is the default+-- if you don't specify a definition for 'ix'.+ixAt :: At m => Index m -> Traversal' m (IxValue m)+ixAt i = at i . traverse+{-# INLINE ixAt #-}++type instance IxValue (e -> a) = a+instance Eq e => Ixed (e -> a) where+  ix e p f = p (f e) <&> \a e' -> if e == e' then a else f e'+  {-# INLINE ix #-}++type instance IxValue (Maybe a) = a+instance Ixed (Maybe a) where+  ix ~() f (Just a) = Just <$> f a+  ix ~() _ Nothing  = pure Nothing+  {-# INLINE ix #-}++type instance IxValue [a] = a+instance Ixed [a] where+  ix k f xs0 | k < 0     = pure xs0+             | otherwise = go xs0 k where+    go [] _ = pure []+    go (a:as) 0 = f a <&> (:as)+    go (a:as) i = (a:) <$> (go as $! i - 1)+  {-# INLINE ix #-}++type instance IxValue (NonEmpty a) = a+instance Ixed (NonEmpty a) where+  ix k f xs0 | k < 0 = pure xs0+             | otherwise = go xs0 k where+    go (a:|as) 0 = f a <&> (:|as)+    go (a:|as) i = (a:|) <$> ix (i - 1) f as+  {-# INLINE ix #-}++type instance IxValue (Identity a) = a+instance Ixed (Identity a) where+  ix ~() f (Identity a) = Identity <$> f a+  {-# INLINE ix #-}++type instance IxValue (Tree a) = a+instance Ixed (Tree a) where+  ix xs0 f = go xs0 where+    go [] (Node a as) = f a <&> \a' -> Node a' as+    go (i:is) t@(Node a as)+      | i < 0     = pure t+      | otherwise = Node a <$> ix i (go is) as+  {-# INLINE ix #-}++type instance IxValue (Seq a) = a+instance Ixed (Seq a) where+  ix i f m+    | 0 <= i && i < Seq.length m = f (Seq.index m i) <&> \a -> Seq.update i a m+    | otherwise                  = pure m+  {-# INLINE ix #-}++type instance IxValue (IntMap a) = a+instance Ixed (IntMap a) where+  ix k f m = case IntMap.lookup k m of+     Just v -> f v <&> \v' -> IntMap.insert k v' m+     Nothing -> pure m+  {-# INLINE ix #-}++type instance IxValue (Map k a) = a+instance Ord k => Ixed (Map k a) where+  ix k f m = case Map.lookup k m of+     Just v  -> f v <&> \v' -> Map.insert k v' m+     Nothing -> pure m+  {-# INLINE ix #-}++type instance IxValue (HashMap k a) = a+instance (Eq k, Hashable k) => Ixed (HashMap k a) where+  ix k f m = case HashMap.lookup k m of+     Just v  -> f v <&> \v' -> HashMap.insert k v' m+     Nothing -> pure m+  {-# INLINE ix #-}++type instance IxValue (Set k) = ()+instance Ord k => Ixed (Set k) where+  ix k f m = if Set.member k m+     then f () $> m+     else pure m+  {-# INLINE ix #-}++type instance IxValue IntSet = ()+instance Ixed IntSet where+  ix k f m = if IntSet.member k m+     then f () $> m+     else pure m+  {-# INLINE ix #-}++type instance IxValue (HashSet k) = ()+instance (Eq k, Hashable k) => Ixed (HashSet k) where+  ix k f m = if HashSet.member k m+     then f () $> m+     else pure m+  {-# INLINE ix #-}++type instance IxValue (Array.Array i e) = e+-- |+-- @+-- arr '!' i ≡ arr 'Control.Lens.Getter.^.' 'ix' i+-- arr '//' [(i,e)] ≡ 'ix' i 'Control.Lens.Setter..~' e '$' arr+-- @+instance Ix i => Ixed (Array.Array i e) where+  ix i f arr+    | inRange (bounds arr) i = f (arr Array.! i) <&> \e -> arr Array.// [(i,e)]+    | otherwise              = pure arr+  {-# INLINE ix #-}++type instance IxValue (UArray i e) = e+-- |+-- @+-- arr '!' i ≡ arr 'Control.Lens.Getter.^.' 'ix' i+-- arr '//' [(i,e)] ≡ 'ix' i 'Control.Lens.Setter..~' e '$' arr+-- @+instance (IArray UArray e, Ix i) => Ixed (UArray i e) where+  ix i f arr+    | inRange (bounds arr) i = f (arr Array.! i) <&> \e -> arr Array.// [(i,e)]+    | otherwise              = pure arr+  {-# INLINE ix #-}++type instance IxValue (Vector.Vector a) = a+instance Ixed (Vector.Vector a) where+  ix i f v+    | 0 <= i && i < Vector.length v = f (v Vector.! i) <&> \a -> v Vector.// [(i, a)]+    | otherwise                     = pure v+  {-# INLINE ix #-}++type instance IxValue (Prim.Vector a) = a+instance Prim a => Ixed (Prim.Vector a) where+  ix i f v+    | 0 <= i && i < Prim.length v = f (v Prim.! i) <&> \a -> v Prim.// [(i, a)]+    | otherwise                   = pure v+  {-# INLINE ix #-}++type instance IxValue (Storable.Vector a) = a+instance Storable a => Ixed (Storable.Vector a) where+  ix i f v+    | 0 <= i && i < Storable.length v = f (v Storable.! i) <&> \a -> v Storable.// [(i, a)]+    | otherwise                       = pure v+  {-# INLINE ix #-}++type instance IxValue (Unboxed.Vector a) = a+instance Unbox a => Ixed (Unboxed.Vector a) where+  ix i f v+    | 0 <= i && i < Unboxed.length v = f (v Unboxed.! i) <&> \a -> v Unboxed.// [(i, a)]+    | otherwise                      = pure v+  {-# INLINE ix #-}++#if MIN_VERSION_vector(0,13,2)+type instance IxValue (VectorStrict.Vector a) = a+instance Ixed (VectorStrict.Vector a) where+  ix i f v+    | 0 <= i && i < VectorStrict.length v = f (v VectorStrict.! i) <&> \a -> v VectorStrict.// [(i, a)]+    | otherwise                           = pure v+  {-# INLINE ix #-}+#endif++type instance IxValue StrictT.Text = Char+instance Ixed StrictT.Text where+  ix e f s +      | e < 0 = pure s+      | otherwise = case StrictT.splitAt e s of+            (l, mr) -> case StrictT.uncons mr of+                Nothing      -> pure s+                Just (c, xs) -> f c <&> \d -> StrictT.concat [l, StrictT.singleton d, xs]+  {-# INLINE ix #-}++type instance IxValue LazyT.Text = Char+instance Ixed LazyT.Text where+  ix e f s +        | e < 0 = pure s+        | otherwise = case LazyT.splitAt e s of+            (l, mr) -> case LazyT.uncons mr of+              Nothing      -> pure s+              Just (c, xs) -> f c <&> \d -> LazyT.append l (LazyT.cons d xs)+  {-# INLINE ix #-}++type instance IxValue StrictB.ByteString = Word8+instance Ixed StrictB.ByteString where+  ix e f s +        | e < 0 = pure s+        | otherwise = case StrictB.splitAt e s of+          (l, mr) -> case StrictB.uncons mr of+            Nothing      -> pure s+            Just (c, xs) -> f c <&> \d -> StrictB.concat [l, StrictB.singleton d, xs]+  {-# INLINE ix #-}++type instance IxValue LazyB.ByteString = Word8+instance Ixed LazyB.ByteString where+  -- TODO: we could be lazier, returning each chunk as it is passed+  ix e f s +        | e < 0 = pure s+        | otherwise =  case LazyB.splitAt e s of+          (l, mr) -> case LazyB.uncons mr of+            Nothing      -> pure s+            Just (c, xs) -> f c <&> \d -> LazyB.append l (LazyB.cons d xs)+  {-# INLINE ix #-}++++-- | 'At' provides a 'Lens' that can be used to read,+-- write or delete the value associated with a key in a 'Map'-like+-- container on an ad hoc basis.+--+-- An instance of 'At' should satisfy:+--+-- @+-- 'ix' k ≡ 'at' k '.' 'traverse'+-- @+class Ixed m => At m where+  -- |+  -- >>> Map.fromList [(1,"world")] ^.at 1+  -- Just "world"+  --+  -- >>> at 1 ?~ "hello" $ Map.empty+  -- fromList [(1,"hello")]+  --+  -- /Note:/ 'Map'-like containers form a reasonable instance, but not 'Array'-like ones, where+  -- you cannot satisfy the 'Lens' laws.+  at :: Index m -> Lens' m (Maybe (IxValue m))++-- | Delete the value associated with a key in a 'Map'-like container+--+-- @+-- 'sans' k = 'at' k .~ Nothing+-- @+sans :: At m => Index m -> m -> m+sans k m = m & at k .~ Nothing+{-# INLINE sans #-}++-- | An indexed version of 'at'.+--+-- >>> Map.fromList [(1,"world")] ^@. iat 1+-- (1,Just "world")+--+-- >>> iat 1 %@~ (\i x -> if odd i then Just "hello" else Nothing) $ Map.empty+-- fromList [(1,"hello")]+--+-- >>> iat 2 %@~ (\i x -> if odd i then Just "hello" else Nothing) $ Map.empty+-- fromList []+--+iat :: At m => Index m -> IndexedLens' (Index m) m (Maybe (IxValue m))+iat i f = at i (indexed f i)+{-# INLINE iat #-}++instance At (Maybe a) where+  at ~() f = f+  {-# INLINE at #-}++instance At (IntMap a) where+#if MIN_VERSION_containers(0,5,8)+  at k f = IntMap.alterF f k+#else+  at k f m = f mv <&> \r -> case r of+    Nothing -> maybe m (const (IntMap.delete k m)) mv+    Just v' -> IntMap.insert k v' m+    where mv = IntMap.lookup k m+#endif+  {-# INLINE at #-}++instance Ord k => At (Map k a) where+#if MIN_VERSION_containers(0,5,8)+  at k f = Map.alterF f k+#else+  at k f m = f mv <&> \r -> case r of+    Nothing -> maybe m (const (Map.delete k m)) mv+    Just v' -> Map.insert k v' m+    where mv = Map.lookup k m+#endif+  {-# INLINE at #-}++instance (Eq k, Hashable k) => At (HashMap k a) where+  at k f = HashMap.alterF f k+  {-# INLINE at #-}++instance At IntSet where+  -- This is a gently modified copy of the implementation of `IntSet.alterF`.+  -- Unlike a `Set`, we don't have to worry about expensive comparisons from+  -- descending multiple times into an `IntSet`. We are careful to share the+  -- results of insertion or deletion across multiple positions in the+  -- `Functor`.+  at k f s = fmap choose (f (guard member_))+    where+      member_ = IntSet.member k s++      (inserted, deleted)+        | member_   = (s, IntSet.delete k s)+        | otherwise = (IntSet.insert k s, s)++      choose (Just ~()) = inserted+      choose Nothing = deleted+  {-# INLINE at #-}++instance Ord k => At (Set k) where+#if MIN_VERSION_containers(0,6,3)+  at k f = Set.alterF (fmap isJust . f . guard) k+#else+  at k f m = f mv <&> \r -> case r of+    Nothing -> maybe m (const (Set.delete k m)) mv+    Just ~() -> maybe (Set.insert k m) (const m) mv+    where mv = if Set.member k m then Just () else Nothing+#endif+  {-# INLINE at #-}++instance (Eq k, Hashable k) => At (HashSet k) where+  at k f s = HashSet.fromMap <$> HashMap.alterF f k (HashSet.toMap s)+  {-# INLINE at #-}+++-- | @'ix' :: 'Int' -> 'Traversal'' (a,a) a@+type instance IxValue (a,a2) = a+instance (a~a2) => Ixed (a,a2) where+  ix p = elementOf each p++-- | @'ix' :: 'Int' -> 'Traversal'' (a,a,a) a@+type instance IxValue (a,a2,a3) = a+instance (a~a2, a~a3) => Ixed (a,a2,a3) where+  ix p = elementOf each p++-- | @'ix' :: 'Int' -> 'Traversal'' (a,a,a,a) a@+type instance IxValue (a,a2,a3,a4) = a+instance (a~a2, a~a3, a~a4) => Ixed (a,a2,a3,a4) where+  ix p = elementOf each p++-- | @'ix' :: 'Int' -> 'Traversal'' (a,a,a,a,a) a@+type instance IxValue (a,a2,a3,a4,a5) = a+instance (a~a2, a~a3, a~a4, a~a5) => Ixed (a,a2,a3,a4,a5) where+  ix p = elementOf each p++-- | @'ix' :: 'Int' -> 'Traversal'' (a,a,a,a,a,a) a@+type instance IxValue (a,a2,a3,a4,a5,a6) = a+instance (a~a2, a~a3, a~a4, a~a5, a~a6) => Ixed (a,a2,a3,a4,a5,a6) where+  ix p = elementOf each p++-- | @'ix' :: 'Int' -> 'Traversal'' (a,a,a,a,a,a,a) a@+type instance IxValue (a,a2,a3,a4,a5,a6,a7) = a+instance (a~a2, a~a3, a~a4, a~a5, a~a6, a~a7) => Ixed (a,a2,a3,a4,a5,a6,a7) where+  ix p = elementOf each p++-- | @'ix' :: 'Int' -> 'Traversal'' (a,a,a,a,a,a,a,a) a@+type instance IxValue (a,a2,a3,a4,a5,a6,a7,a8) = a+instance (a~a2, a~a3, a~a4, a~a5, a~a6, a~a7, a~a8) => Ixed (a,a2,a3,a4,a5,a6,a7,a8) where+  ix p = elementOf each p++-- | @'ix' :: 'Int' -> 'Traversal'' (a,a,a,a,a,a,a,a,a) a@+type instance IxValue (a,a2,a3,a4,a5,a6,a7,a8,a9) = a+instance (a~a2, a~a3, a~a4, a~a5, a~a6, a~a7, a~a8, a~a9) => Ixed (a,a2,a3,a4,a5,a6,a7,a8,a9) where+  ix p = elementOf each p
src/Control/Lens/Combinators.hs view
@@ -1,35 +1,158 @@--------------------------------------------------------------------------------+{-# Language CPP #-}+-------------------------------------------------------------------------------- -- | -- Module      :  Control.Lens.Combinators--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2013-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  portable+-- Stability   :  experimental+-- Portability :  non-portable -----------------------------------------------------------------------------------module Control.Lens.Combinators-  ( (<$!>), (<$!)-  ) where--infixr 4 <$!>, <$!---- | A strict version of ('Data.Functor.<$>') for monads.+-- This lets the subset of users who vociferously disagree about the full+-- scope and set of operators that should be exported from lens to not have+-- to look at any operator with which they disagree. ----- >>> (+1) <$!> [1,2,3,4]--- [2,3,4,5]-(<$!>) :: Monad m => (a -> b) -> m a -> m b-f <$!> m = do-  a <- m-  return $! f a-{-# INLINE (<$!>) #-}+-- > import Control.Lens.Combinators+--------------------------------------------------------------------------------+module Control.Lens.Combinators+    ( module Control.Lens+    ) where --- | A strict version of ('Data.Functor.<$') for monads.------ >>> () <$! [1,2,3,4]--- [(),(),(),()]-(<$!) :: Monad m => b -> m a -> m b-b <$! m = do-  _ <- m-  return $! b-{-# INLINE (<$!) #-}+import Control.Lens hiding+  ( (<|)+  , (|>)+  , (^..)+  , (^?)+  , (^?!)+  , (^@..)+  , (^@?)+  , (^@?!)+  , (^.)+  , (^@.)+  , (<.)+  , (.>)+  , (<.>)+  , (%%~)+  , (%%=)+  , (&)+  , (&~)+  , (<&>)+  , (??)+  , (<%~)+  , (<+~)+  , (<-~)+  , (<*~)+  , (<//~)+  , (<^~)+  , (<^^~)+  , (<**~)+  , (<||~)+  , (<&&~)+  , (<<%~)+  , (<<.~)+  , (<<+~)+  , (<<-~)+  , (<<*~)+  , (<<//~)+  , (<<^~)+  , (<<^^~)+  , (<<**~)+  , (<<||~)+  , (<<&&~)+  , (<<<>~)+  , (<%=)+  , (<+=)+  , (<-=)+  , (<*=)+  , (<//=)+  , (<^=)+  , (<^^=)+  , (<**=)+  , (<||=)+  , (<&&=)+  , (<<%=)+  , (<<.=)+  , (<<+=)+  , (<<-=)+  , (<<*=)+  , (<<//=)+  , (<<^=)+  , (<<^^=)+  , (<<**=)+  , (<<||=)+  , (<<&&=)+  , (<<<>=)+  , (<<~)+  , (<<>~)+  , (<<>=)+  , (<%@~)+  , (<<%@~)+  , (%%@~)+  , (%%@=)+  , (<%@=)+  , (<<%@=)+  , (.@=)+  , (.@~)+  , (^#)+  , (#~)+  , (#%~)+  , (#%%~)+  , (#=)+  , (#%=)+  , (<#%~)+  , (<#%=)+  , (#%%=)+  , (<#~)+  , (<#=)+  , (...)+  , (#)+  , (%~)+  , (.~)+  , (?~)+  , (<.~)+  , (<?~)+  , (<<?~)+  , (<<?=)+  , (+~)+  , (*~)+  , (-~)+  , (//~)+  , (^~)+  , (^^~)+  , (**~)+  , (||~)+  , (&&~)+  , (.=)+  , (%=)+  , (?=)+  , (+=)+  , (-=)+  , (*=)+  , (//=)+  , (^=)+  , (^^=)+  , (**=)+  , (&&=)+  , (||=)+  , (<~)+  , (<.=)+  , (<?=)+  , (<>~)+  , (<>=)+  , (<>:~)+  , (<>:=)+  , (<<>:~)+  , (<<>:=)+  , (<|~)+  , (<|=)+  , (<<|~)+  , (<<|=)+  , (|>~)+  , (|>=)+  , (<|>~)+  , (<|>=)+  , (%@~)+  , (%@=)+  , (:>)+  , (:<)+  )
+ src/Control/Lens/Cons.hs view
@@ -0,0 +1,645 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-}+#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-}+#endif+-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Cons+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-----------------------------------------------------------------------------+module Control.Lens.Cons+  (+  -- * Cons+    Cons(..)+  , (<|)+  , cons+  , uncons+  , _head, _tail+  , (<|~), (<|=), (<<|~), (<<|=), (<<<|~), (<<<|=)+  , pattern (:<)+  -- * Snoc+  , Snoc(..)+  , (|>)+  , snoc+  , unsnoc+  , _init, _last+  , (|>~), (|>=), (<|>~), (<|>=), (<<|>~), (<<|>=)+  , pattern (:>)++  ) where++import Control.Lens.Equality (simply)+import Control.Lens.Fold+import Control.Lens.Lens+import Control.Lens.Prism+import Control.Lens.Review+import Control.Lens.Setter+import Control.Lens.Tuple+import Control.Lens.Type+import qualified Data.ByteString      as StrictB+import qualified Data.ByteString.Lazy as LazyB+import           Data.Coerce+import           Data.Monoid+import qualified Data.Sequence as Seq+import           Data.Sequence (Seq, ViewL(EmptyL), ViewR(EmptyR), viewl, viewr)+import qualified Data.Text      as StrictT+import qualified Data.Text.Lazy as LazyT+import           Data.Vector (Vector)+import qualified Data.Vector as Vector+import           Data.Vector.Storable (Storable)+import qualified Data.Vector.Storable as Storable+import           Data.Vector.Primitive (Prim)+import qualified Data.Vector.Primitive as Prim+import           Data.Vector.Unboxed (Unbox)+import qualified Data.Vector.Unboxed as Unbox+#if MIN_VERSION_vector(0,13,2)+import qualified Data.Vector.Strict as VectorStrict+#endif+import           Data.Word+import           Control.Applicative (ZipList(..))+import           Control.Monad.State.Class as State+import           Prelude++-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import qualified Data.Sequence as Seq+-- >>> import qualified Data.Vector as Vector+-- >>> import qualified Data.Text.Lazy as LazyT+-- >>> import Debug.SimpleReflect.Expr+-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g)+-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f+-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g++infixr 5 <|, `cons`+infixl 5 |>, `snoc`+infixr 4 <|~, |>~, <<|~, <|>~, <<<|~, <<|>~+infix  4 <|=, |>=, <<|=, <|>=, <<<|=, <<|>=++pattern (:<) :: Cons b b a a => a -> b -> b+pattern (:<) a s <- (preview _Cons -> Just (a,s)) where+  (:<) a s = _Cons # (a,s)++infixr 5 :<+infixl 5 :>++pattern (:>) :: Snoc a a b b => a -> b -> a+pattern (:>) s a <- (preview _Snoc -> Just (s,a)) where+  (:>) a s = _Snoc # (a,s)++------------------------------------------------------------------------------+-- Cons+------------------------------------------------------------------------------++-- | This class provides a way to attach or detach elements on the left+-- side of a structure in a flexible manner.+class Cons s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- |+  --+  -- @+  -- '_Cons' :: 'Prism' [a] [b] (a, [a]) (b, [b])+  -- '_Cons' :: 'Prism' ('Seq' a) ('Seq' b) (a, 'Seq' a) (b, 'Seq' b)+  -- '_Cons' :: 'Prism' ('Vector' a) ('Vector' b) (a, 'Vector' a) (b, 'Vector' b)+  -- '_Cons' :: 'Prism'' 'String' ('Char', 'String')+  -- '_Cons' :: 'Prism'' 'StrictT.Text' ('Char', 'StrictT.Text')+  -- '_Cons' :: 'Prism'' 'StrictB.ByteString' ('Word8', 'StrictB.ByteString')+  -- @+  _Cons :: Prism s t (a,s) (b,t)++instance Cons [a] [b] a b where+  _Cons = prism (uncurry (:)) $ \ aas -> case aas of+    (a:as) -> Right (a, as)+    []     -> Left  []+  {-# INLINE _Cons #-}++instance Cons (ZipList a) (ZipList b) a b where+  _Cons = withPrism listCons $ \listReview listPreview ->+    prism (coerce listReview) (coerce listPreview) where++    listCons :: Prism [a] [b] (a, [a]) (b, [b])+    listCons = _Cons++  {-# INLINE _Cons #-}++instance Cons (Seq a) (Seq b) a b where+  _Cons = prism (uncurry (Seq.<|)) $ \aas -> case viewl aas of+    a Seq.:< as -> Right (a, as)+    EmptyL  -> Left mempty+  {-# INLINE _Cons #-}++instance Cons StrictB.ByteString StrictB.ByteString Word8 Word8 where+  _Cons = prism' (uncurry StrictB.cons) StrictB.uncons+  {-# INLINE _Cons #-}++instance Cons LazyB.ByteString LazyB.ByteString Word8 Word8 where+  _Cons = prism' (uncurry LazyB.cons) LazyB.uncons+  {-# INLINE _Cons #-}++instance Cons StrictT.Text StrictT.Text Char Char where+  _Cons = prism' (uncurry StrictT.cons) StrictT.uncons+  {-# INLINE _Cons #-}++instance Cons LazyT.Text LazyT.Text Char Char where+  _Cons = prism' (uncurry LazyT.cons) LazyT.uncons+  {-# INLINE _Cons #-}++instance Cons (Vector a) (Vector b) a b where+  _Cons = prism (uncurry Vector.cons) $ \v ->+    if Vector.null v+    then Left Vector.empty+    else Right (Vector.unsafeHead v, Vector.unsafeTail v)+  {-# INLINE _Cons #-}++instance (Prim a, Prim b) => Cons (Prim.Vector a) (Prim.Vector b) a b where+  _Cons = prism (uncurry Prim.cons) $ \v ->+    if Prim.null v+    then Left Prim.empty+    else Right (Prim.unsafeHead v, Prim.unsafeTail v)+  {-# INLINE _Cons #-}++instance (Storable a, Storable b) => Cons (Storable.Vector a) (Storable.Vector b) a b where+  _Cons = prism (uncurry Storable.cons) $ \v ->+    if Storable.null v+    then Left Storable.empty+    else Right (Storable.unsafeHead v, Storable.unsafeTail v)+  {-# INLINE _Cons #-}++instance (Unbox a, Unbox b) => Cons (Unbox.Vector a) (Unbox.Vector b) a b where+  _Cons = prism (uncurry Unbox.cons) $ \v ->+    if Unbox.null v+    then Left Unbox.empty+    else Right (Unbox.unsafeHead v, Unbox.unsafeTail v)+  {-# INLINE _Cons #-}++#if MIN_VERSION_vector(0,13,2)+instance Cons (VectorStrict.Vector a) (VectorStrict.Vector b) a b where+  _Cons = prism (uncurry VectorStrict.cons) $ \v ->+    if VectorStrict.null v+    then Left VectorStrict.empty+    else Right (VectorStrict.unsafeHead v, VectorStrict.unsafeTail v)+  {-# INLINE _Cons #-}+#endif++-- | 'cons' an element onto a container.+--+-- This is an infix alias for 'cons'.+--+-- >>> a <| []+-- [a]+--+-- >>> a <| [b, c]+-- [a,b,c]+--+-- >>> a <| Seq.fromList []+-- fromList [a]+--+-- >>> a <| Seq.fromList [b, c]+-- fromList [a,b,c]+(<|) :: Cons s s a a => a -> s -> s+(<|) = curry (simply review _Cons)+{-# INLINE (<|) #-}++-- | 'cons' an element onto a container.+--+-- >>> cons a []+-- [a]+--+-- >>> cons a [b, c]+-- [a,b,c]+--+-- >>> cons a (Seq.fromList [])+-- fromList [a]+--+-- >>> cons a (Seq.fromList [b, c])+-- fromList [a,b,c]+cons :: Cons s s a a => a -> s -> s+cons = curry (simply review _Cons)+{-# INLINE cons #-}++-- | Attempt to extract the left-most element from a container, and a version of the container without that element.+--+-- >>> uncons []+-- Nothing+--+-- >>> uncons [a, b, c]+-- Just (a,[b,c])+uncons :: Cons s s a a => s -> Maybe (a, s)+uncons = simply preview _Cons+{-# INLINE uncons #-}++-- | A 'Traversal' reading and writing to the 'head' of a /non-empty/ container.+--+-- >>> [a,b,c]^? _head+-- Just a+--+-- >>> [a,b,c] & _head .~ d+-- [d,b,c]+--+-- >>> [a,b,c] & _head %~ f+-- [f a,b,c]+--+-- >>> [] & _head %~ f+-- []+--+-- >>> [1,2,3]^?!_head+-- 1+--+-- >>> []^?_head+-- Nothing+--+-- >>> [1,2]^?_head+-- Just 1+--+-- >>> [] & _head .~ 1+-- []+--+-- >>> [0] & _head .~ 2+-- [2]+--+-- >>> [0,1] & _head .~ 2+-- [2,1]+--+-- This isn't limited to lists.+--+-- For instance you can also 'Data.Traversable.traverse' the head of a 'Seq':+--+-- >>> Seq.fromList [a,b,c,d] & _head %~ f+-- fromList [f a,b,c,d]+--+-- >>> Seq.fromList [] ^? _head+-- Nothing+--+-- >>> Seq.fromList [a,b,c,d] ^? _head+-- Just a+--+-- @+-- '_head' :: 'Traversal'' [a] a+-- '_head' :: 'Traversal'' ('Seq' a) a+-- '_head' :: 'Traversal'' ('Vector' a) a+-- @+_head :: Cons s s a a => Traversal' s a+_head = _Cons._1+{-# INLINE _head #-}++-- | A 'Traversal' reading and writing to the 'tail' of a /non-empty/ container.+--+-- >>> [a,b] & _tail .~ [c,d,e]+-- [a,c,d,e]+--+-- >>> [] & _tail .~ [a,b]+-- []+--+-- >>> [a,b,c,d,e] & _tail.traverse %~ f+-- [a,f b,f c,f d,f e]+--+-- >>> [1,2] & _tail .~ [3,4,5]+-- [1,3,4,5]+--+-- >>> [] & _tail .~ [1,2]+-- []+--+-- >>> [a,b,c]^?_tail+-- Just [b,c]+--+-- >>> [1,2]^?!_tail+-- [2]+--+-- >>> "hello"^._tail+-- "ello"+--+-- >>> ""^._tail+-- ""+--+-- This isn't limited to lists. For instance you can also 'Control.Traversable.traverse' the tail of a 'Seq'.+--+-- >>> Seq.fromList [a,b] & _tail .~ Seq.fromList [c,d,e]+-- fromList [a,c,d,e]+--+-- >>> Seq.fromList [a,b,c] ^? _tail+-- Just (fromList [b,c])+--+-- >>> Seq.fromList [] ^? _tail+-- Nothing+--+-- @+-- '_tail' :: 'Traversal'' [a] [a]+-- '_tail' :: 'Traversal'' ('Seq' a) ('Seq' a)+-- '_tail' :: 'Traversal'' ('Vector' a) ('Vector' a)+-- @+_tail :: Cons s s a a => Traversal' s s+_tail = _Cons._2+{-# INLINE _tail #-}++-- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' using @('<|')@.+--+-- >>> (["world"], ["lens"]) & _1 <|~ "hello"+-- (["hello","world"],["lens"])+(<|~) :: Cons b b a a => ASetter s t b b -> a -> s -> t+l <|~ n = over l (n <|)+{-# INLINE (<|~) #-}++-- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' using @('<|')@.+(<|=) :: (MonadState s m, Cons b b a a) => ASetter s s b b -> a -> m ()+l <|= a = State.modify (l <|~ a)+{-# INLINE (<|=) #-}++-- | ('<|') a value onto the target of a 'Lens' and return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Cons.<|~') is more flexible.+(<<|~) :: Cons b b a a => LensLike ((,) b) s t b b -> a -> s -> (b, t)+l <<|~ m = l <%~ (m <|)+{-# INLINE (<<|~) #-}++-- | ('<|') a value onto the target of a 'Lens' and return the /old/ result.+--+-- When you do not need the result of the operation, ('Control.Lens.Cons.<|~') is more flexible.+(<<<|~) :: Cons b b a a => LensLike' ((,) b) s b -> a -> s -> (b, s)+l <<<|~ m = l <<%~ (m <|)+{-# INLINE (<<<|~) #-}++-- | ('<|') a value onto the target of a 'Lens' into your 'Monad'\'s state and+-- return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Cons.<|=') is more flexible.+(<<|=) :: (MonadState s m, Cons b b a a) => LensLike ((,) b) s s b b -> a -> m b+l <<|= r = l <%= (r <|)+{-# INLINE (<<|=) #-}++-- | ('<|') a value onto the target of a 'Lens' into your 'Monad'\'s state and+-- return the /old/ result.+--+-- When you do not need the result of the operation, ('Control.Lens.Cons.<|=') is more flexible.+(<<<|=) :: (MonadState s m, Cons b b a a) => LensLike ((,) b) s s b b -> a -> m b+l <<<|= r = l <<%= (r <|)+{-# INLINE (<<<|=) #-}++------------------------------------------------------------------------------+-- Snoc+------------------------------------------------------------------------------++-- | This class provides a way to attach or detach elements on the right+-- side of a structure in a flexible manner.+class Snoc s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- |+  --+  -- @+  -- '_Snoc' :: 'Prism' [a] [b] ([a], a) ([b], b)+  -- '_Snoc' :: 'Prism' ('Seq' a) ('Seq' b) ('Seq' a, a) ('Seq' b, b)+  -- '_Snoc' :: 'Prism' ('Vector' a) ('Vector' b) ('Vector' a, a) ('Vector' b, b)+  -- '_Snoc' :: 'Prism'' 'String' ('String', 'Char')+  -- '_Snoc' :: 'Prism'' 'StrictT.Text' ('StrictT.Text', 'Char')+  -- '_Snoc' :: 'Prism'' 'StrictB.ByteString' ('StrictB.ByteString', 'Word8')+  -- @+  _Snoc :: Prism s t (s,a) (t,b)++instance Snoc [a] [b] a b where+  _Snoc = prism (\(as,a) -> as Prelude.++ [a]) $ \aas -> if Prelude.null aas+    then Left []+    else Right (Prelude.init aas, Prelude.last aas)+  {-# INLINE _Snoc #-}++instance Snoc (ZipList a) (ZipList b) a b where+  _Snoc = withPrism listSnoc $ \listReview listPreview ->+    prism (coerce listReview) (coerce listPreview) where++    listSnoc :: Prism [a] [b] ([a], a) ([b], b)+    listSnoc = _Snoc++  {-# INLINE _Snoc #-}++instance Snoc (Seq a) (Seq b) a b where+  _Snoc = prism (uncurry (Seq.|>)) $ \aas -> case viewr aas of+    as Seq.:> a -> Right (as, a)+    EmptyR  -> Left mempty+  {-# INLINE _Snoc #-}++instance Snoc (Vector a) (Vector b) a b where+  _Snoc = prism (uncurry Vector.snoc) $ \v -> if Vector.null v+    then Left Vector.empty+    else Right (Vector.unsafeInit v, Vector.unsafeLast v)+  {-# INLINE _Snoc #-}++instance (Prim a, Prim b) => Snoc (Prim.Vector a) (Prim.Vector b) a b where+  _Snoc = prism (uncurry Prim.snoc) $ \v -> if Prim.null v+    then Left Prim.empty+    else Right (Prim.unsafeInit v, Prim.unsafeLast v)+  {-# INLINE _Snoc #-}++instance (Storable a, Storable b) => Snoc (Storable.Vector a) (Storable.Vector b) a b where+  _Snoc = prism (uncurry Storable.snoc) $ \v -> if Storable.null v+    then Left Storable.empty+    else Right (Storable.unsafeInit v, Storable.unsafeLast v)+  {-# INLINE _Snoc #-}++instance (Unbox a, Unbox b) => Snoc (Unbox.Vector a) (Unbox.Vector b) a b where+  _Snoc = prism (uncurry Unbox.snoc) $ \v -> if Unbox.null v+    then Left Unbox.empty+    else Right (Unbox.unsafeInit v, Unbox.unsafeLast v)+  {-# INLINE _Snoc #-}++instance Snoc StrictB.ByteString StrictB.ByteString Word8 Word8 where+  _Snoc = prism (uncurry StrictB.snoc) $ \v -> if StrictB.null v+    then Left StrictB.empty+    else Right (StrictB.init v, StrictB.last v)+  {-# INLINE _Snoc #-}++instance Snoc LazyB.ByteString LazyB.ByteString Word8 Word8 where+  _Snoc = prism (uncurry LazyB.snoc) $ \v -> if LazyB.null v+    then Left LazyB.empty+    else Right (LazyB.init v, LazyB.last v)+  {-# INLINE _Snoc #-}++instance Snoc StrictT.Text StrictT.Text Char Char where+  _Snoc = prism (uncurry StrictT.snoc) $ \v -> if StrictT.null v+    then Left StrictT.empty+    else Right (StrictT.init v, StrictT.last v)+  {-# INLINE _Snoc #-}++instance Snoc LazyT.Text LazyT.Text Char Char where+  _Snoc = prism (uncurry LazyT.snoc) $ \v -> if LazyT.null v+    then Left LazyT.empty+    else Right (LazyT.init v, LazyT.last v)+  {-# INLINE _Snoc #-}++-- | A 'Traversal' reading and replacing all but the a last element of a /non-empty/ container.+--+-- >>> [a,b,c,d]^?_init+-- Just [a,b,c]+--+-- >>> []^?_init+-- Nothing+--+-- >>> [a,b] & _init .~ [c,d,e]+-- [c,d,e,b]+--+-- >>> [] & _init .~ [a,b]+-- []+--+-- >>> [a,b,c,d] & _init.traverse %~ f+-- [f a,f b,f c,d]+--+-- >>> [1,2,3]^?_init+-- Just [1,2]+--+-- >>> [1,2,3,4]^?!_init+-- [1,2,3]+--+-- >>> "hello"^._init+-- "hell"+--+-- >>> ""^._init+-- ""+--+-- @+-- '_init' :: 'Traversal'' [a] [a]+-- '_init' :: 'Traversal'' ('Seq' a) ('Seq' a)+-- '_init' :: 'Traversal'' ('Vector' a) ('Vector' a)+-- @+_init :: Snoc s s a a => Traversal' s s+_init = _Snoc._1+{-# INLINE _init #-}++-- | A 'Traversal' reading and writing to the last element of a /non-empty/ container.+--+-- >>> [a,b,c]^?!_last+-- c+--+-- >>> []^?_last+-- Nothing+--+-- >>> [a,b,c] & _last %~ f+-- [a,b,f c]+--+-- >>> [1,2]^?_last+-- Just 2+--+-- >>> [] & _last .~ 1+-- []+--+-- >>> [0] & _last .~ 2+-- [2]+--+-- >>> [0,1] & _last .~ 2+-- [0,2]+--+-- This 'Traversal' is not limited to lists, however. We can also work with other containers, such as a 'Vector'.+--+-- >>> Vector.fromList "abcde" ^? _last+-- Just 'e'+--+-- >>> Vector.empty ^? _last+-- Nothing+--+-- >>> (Vector.fromList "abcde" & _last .~ 'Q') == Vector.fromList "abcdQ"+-- True+--+-- @+-- '_last' :: 'Traversal'' [a] a+-- '_last' :: 'Traversal'' ('Seq' a) a+-- '_last' :: 'Traversal'' ('Vector' a) a+-- @+_last :: Snoc s s a a => Traversal' s a+_last = _Snoc._2+{-# INLINE _last #-}++-- | 'snoc' an element onto a container.+--+-- This is an infix alias for 'snoc'.+--+-- >>> Seq.fromList [] |> a+-- fromList [a]+--+-- >>> Seq.fromList [b, c] |> a+-- fromList [b,c,a]+--+-- >>> LazyT.pack "hello" |> '!'+-- "hello!"+(|>) :: Snoc s s a a => s -> a -> s+(|>) = curry (simply review _Snoc)+{-# INLINE (|>) #-}++-- | 'snoc' an element onto a container.+--+-- >>> snoc (Seq.fromList []) a+-- fromList [a]+--+-- >>> snoc (Seq.fromList [b, c]) a+-- fromList [b,c,a]+--+-- >>> snoc (LazyT.pack "hello") '!'+-- "hello!"+snoc  :: Snoc s s a a => s -> a -> s+snoc = curry (simply review _Snoc)+{-# INLINE snoc #-}++-- | Attempt to extract the right-most element from a container, and a version of the container without that element.+--+-- >>> unsnoc (LazyT.pack "hello!")+-- Just ("hello",'!')+--+-- >>> unsnoc (LazyT.pack "")+-- Nothing+--+-- >>> unsnoc (Seq.fromList [b,c,a])+-- Just (fromList [b,c],a)+--+-- >>> unsnoc (Seq.fromList [])+-- Nothing+unsnoc :: Snoc s s a a => s -> Maybe (s, a)+unsnoc = simply preview _Snoc+{-# INLINE unsnoc #-}++-- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' using @('|>')@.+--+-- >>> (["world"], ["lens"]) & _1 |>~ "hello"+-- (["world","hello"],["lens"])+(|>~) :: Snoc b b a a => ASetter s t b b -> a -> s -> t+l |>~ n = over l (|> n)+{-# INLINE (|>~) #-}++-- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' using @('|>')@.+(|>=) :: (MonadState s m, Snoc b b a a) => ASetter s s b b -> a -> m ()+l |>= a = State.modify (l |>~ a)+{-# INLINE (|>=) #-}++-- | ('|>') a value onto the target of a 'Lens' and return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Cons.|>~') is more flexible.+(<|>~) :: Snoc b b p p => LensLike ((,) b) s t b b -> p -> s -> (b, t)+l <|>~ m = l <%~ (|> m)+{-# INLINE (<|>~) #-}++-- | ('|>') a value onto the target of a 'Lens' and return the /old/ result.+--+-- When you do not need the result of the operation, ('Control.Lens.Cons.|>~') is more flexible.+(<<|>~) :: Snoc b b p p => LensLike' ((,) b) s b -> p -> s -> (b, s)+l <<|>~ m = l <<%~ (|> m)+{-# INLINE (<<|>~) #-}++-- | ('|>') a value onto the target of a 'Lens' into your 'Monad'\'s state and+-- return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Cons.|>=') is more flexible.+(<|>=) :: (MonadState s m, Snoc b b p p) => LensLike ((,) b) s s b b -> p -> m b+l <|>= r = l <%= (|> r)+{-# INLINE (<|>=) #-}++-- | ('|>') a value onto the target of a 'Lens' into your 'Monad'\'s state and+-- return the /old/ result.+--+-- When you do not need the result of the operation, ('Control.Lens.Cons.|>=') is more flexible.+(<<|>=) :: (MonadState s m, Snoc b b p p) => LensLike ((,) b) s s b b -> p -> m b+l <<|>= r = l <<%= (|> r)+{-# INLINE (<<|>=) #-}
+ src/Control/Lens/Each.hs view
@@ -0,0 +1,270 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE DefaultSignatures #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-}+#endif++#include "lens-common.h"++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Each+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-----------------------------------------------------------------------------+module Control.Lens.Each+  (+  -- * Each+    Each(..)+  ) where++import Prelude ()++import Control.Lens.Traversal+import Control.Lens.Internal.ByteString+import Control.Lens.Internal.Prelude+import Data.Array.Unboxed as Unboxed+import Data.Array.IArray as IArray+import qualified Data.ByteString as StrictB+import qualified Data.ByteString.Lazy as LazyB+import Data.Complex+import Data.HashMap.Lazy (HashMap)+import Data.IntMap (IntMap)+import Data.Map (Map)+import Data.Sequence (Seq)+import Data.Text.Lens (text)+import qualified Data.Text as StrictT+import qualified Data.Text.Lazy as LazyT+import Data.Tree as Tree+import Data.Vector.Generic.Lens (vectorTraverse)+import qualified Data.Vector as Vector+import qualified Data.Vector.Primitive as Prim+import Data.Vector.Primitive (Prim)+import qualified Data.Vector.Storable as Storable+import Data.Vector.Storable (Storable)+import qualified Data.Vector.Unboxed as Unboxed+#if MIN_VERSION_vector(0,13,2)+import qualified Data.Vector.Strict as VectorStrict+#endif+import Data.Vector.Unboxed (Unbox)+import Data.Word+import qualified Data.Strict as S+import Data.These (These (..))++-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import Data.Text.Strict.Lens as Text+-- >>> import Data.Char as Char++-- | Extract 'each' element of a (potentially monomorphic) container.+--+-- Notably, when applied to a tuple, this generalizes 'Control.Lens.Traversal.both' to arbitrary homogeneous tuples.+--+-- >>> (1,2,3) & each *~ 10+-- (10,20,30)+--+-- It can also be used on monomorphic containers like 'StrictT.Text' or 'StrictB.ByteString'.+--+-- >>> over each Char.toUpper ("hello"^.Text.packed)+-- "HELLO"+--+-- >>> ("hello","world") & each.each %~ Char.toUpper+-- ("HELLO","WORLD")+class Each s t a b | s -> a, t -> b, s b -> t, t a -> s where+  each :: Traversal s t a b+  default each :: (Traversable g, s ~ g a, t ~ g b) => Traversal s t a b+  each = traverse+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' (a,a) (b,b) a b@+instance (a~a', b~b') => Each (a,a') (b,b') a b where+  each f ~(a,b) = (,) <$> f a <*> f b+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' (a,a,a) (b,b,b) a b@+instance (a~a2, a~a3, b~b2, b~b3) => Each (a,a2,a3) (b,b2,b3) a b where+  each f ~(a,b,c) = (,,) <$> f a <*> f b <*> f c+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' (a,a,a,a) (b,b,b,b) a b@+instance (a~a2, a~a3, a~a4, b~b2, b~b3, b~b4) => Each (a,a2,a3,a4) (b,b2,b3,b4) a b where+  each f ~(a,b,c,d) = (,,,) <$> f a <*> f b <*> f c <*> f d+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' (a,a,a,a,a) (b,b,b,b,b) a b@+instance (a~a2, a~a3, a~a4, a~a5, b~b2, b~b3, b~b4, b~b5) => Each (a,a2,a3,a4,a5) (b,b2,b3,b4,b5) a b where+  each f ~(a,b,c,d,e) = (,,,,) <$> f a <*> f b <*> f c <*> f d <*> f e+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' (a,a,a,a,a,a) (b,b,b,b,b,b) a b@+instance (a~a2, a~a3, a~a4, a~a5, a~a6, b~b2, b~b3, b~b4, b~b5, b~b6) => Each (a,a2,a3,a4,a5,a6) (b,b2,b3,b4,b5,b6) a b where+  each f ~(a,b,c,d,e,g) = (,,,,,) <$> f a <*> f b <*> f c <*> f d <*> f e <*> f g+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' (a,a,a,a,a,a,a) (b,b,b,b,b,b,b) a b@+instance (a~a2, a~a3, a~a4, a~a5, a~a6, a~a7, b~b2, b~b3, b~b4, b~b5, b~b6, b~b7) => Each (a,a2,a3,a4,a5,a6,a7) (b,b2,b3,b4,b5,b6,b7) a b where+  each f ~(a,b,c,d,e,g,h) = (,,,,,,) <$> f a <*> f b <*> f c <*> f d <*> f e <*> f g <*> f h+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' (a,a,a,a,a,a,a,a) (b,b,b,b,b,b,b,b) a b@+instance (a~a2, a~a3, a~a4, a~a5, a~a6, a~a7, a~a8, b~b2, b~b3, b~b4, b~b5, b~b6, b~b7, b~b8) => Each (a,a2,a3,a4,a5,a6,a7,a8) (b,b2,b3,b4,b5,b6,b7,b8) a b where+  each f ~(a,b,c,d,e,g,h,i) = (,,,,,,,) <$> f a <*> f b <*> f c <*> f d <*> f e <*> f g <*> f h <*> f i+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' (a,a,a,a,a,a,a,a,a) (b,b,b,b,b,b,b,b,b) a b@+instance (a~a2, a~a3, a~a4, a~a5, a~a6, a~a7, a~a8, a~a9, b~b2, b~b3, b~b4, b~b5, b~b6, b~b7, b~b8, b~b9) => Each (a,a2,a3,a4,a5,a6,a7,a8,a9) (b,b2,b3,b4,b5,b6,b7,b8,b9) a b where+  each f ~(a,b,c,d,e,g,h,i,j) = (,,,,,,,,) <$> f a <*> f b <*> f c <*> f d <*> f e <*> f g <*> f h <*> f i <*> f j+  {-# INLINE each #-}++-- | @'each' :: ('RealFloat' a, 'RealFloat' b) => 'Traversal' ('Complex' a) ('Complex' b) a b@+instance Each (Complex a) (Complex b) a b where+  each f (a :+ b) = (:+) <$> f a <*> f b+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' ('Map' c a) ('Map' c b) a b@+instance (c ~ d) => Each (Map c a) (Map d b) a b where+  each = traversed+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' ('Map' c a) ('Map' c b) a b@+instance Each (IntMap a) (IntMap b) a b where+  each = traversed+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' ('HashMap' c a) ('HashMap' c b) a b@+instance (c ~ d) => Each (HashMap c a) (HashMap d b) a b where+  each = traversed+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' [a] [b] a b@+instance Each [a] [b] a b where+  each = traversed+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' (NonEmpty a) (NonEmpty b) a b@+instance Each (NonEmpty a) (NonEmpty b) a b++-- | @'each' :: 'Traversal' ('Identity' a) ('Identity' b) a b@+instance Each (Identity a) (Identity b) a b++-- | @'each' :: 'Traversal' ('Maybe' a) ('Maybe' b) a b@+instance Each (Maybe a) (Maybe b) a b++-- | @'each' :: 'Traversal' ('Either' a a) ('Either' b b) a b@+--+-- @since 4.18+instance (a~a', b~b') => Each (Either a a') (Either b b') a b where+  each f (Left a)   = Left <$> f a+  each f (Right a ) = Right <$> f a+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' ('Seq' a) ('Seq' b) a b@+instance Each (Seq a) (Seq b) a b where+  each = traversed+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' ('Tree' a) ('Tree' b) a b@+instance Each (Tree a) (Tree b) a b++-- | @'each' :: 'Traversal' ('Vector.Vector' a) ('Vector.Vector' b) a b@+instance Each (Vector.Vector a) (Vector.Vector b) a b where+  each = vectorTraverse+  {-# INLINE each #-}++-- | @'each' :: ('Prim' a, 'Prim' b) => 'Traversal' ('Prim.Vector' a) ('Prim.Vector' b) a b@+instance (Prim a, Prim b) => Each (Prim.Vector a) (Prim.Vector b) a b where+  each = vectorTraverse+  {-# INLINE each #-}++-- | @'each' :: ('Storable' a, 'Storable' b) => 'Traversal' ('Storable.Vector' a) ('Storable.Vector' b) a b@+instance (Storable a, Storable b) => Each (Storable.Vector a) (Storable.Vector b) a b where+  each = vectorTraverse+  {-# INLINE each #-}++-- | @'each' :: ('Unbox' a, 'Unbox' b) => 'Traversal' ('Unboxed.Vector' a) ('Unboxed.Vector' b) a b@+instance (Unbox a, Unbox b) => Each (Unboxed.Vector a) (Unboxed.Vector b) a b where+  each = vectorTraverse+  {-# INLINE each #-}++#if MIN_VERSION_vector(0,13,2)+-- | @'each' :: 'Traversal' ('Vector.Vector' a) ('Vector.Vector' b) a b@+instance Each (VectorStrict.Vector a) (VectorStrict.Vector b) a b where+  each = vectorTraverse+  {-# INLINE each #-}+#endif++-- | @'each' :: 'Traversal' 'StrictT.Text' 'StrictT.Text' 'Char' 'Char'@+instance (a ~ Char, b ~ Char) => Each StrictT.Text StrictT.Text a b where+  each = text+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' 'LazyT.Text' 'LazyT.Text' 'Char' 'Char'@+instance (a ~ Char, b ~ Char) => Each LazyT.Text LazyT.Text a b where+  each = text+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' 'StrictB.ByteString' 'StrictB.ByteString' 'Word8' 'Word8'@+instance (a ~ Word8, b ~ Word8) => Each StrictB.ByteString StrictB.ByteString a b where+  each = traversedStrictTree+  {-# INLINE each #-}++-- | @'each' :: 'Traversal' 'LazyB.ByteString' 'LazyB.ByteString' 'Word8' 'Word8'@+instance (a ~ Word8, b ~ Word8) => Each LazyB.ByteString LazyB.ByteString a b where+  each = traversedLazy+  {-# INLINE each #-}++-- | @'each' :: 'Ix' i => 'Traversal' ('Array' i a) ('Array' i b) a b@+instance (Ix i, i ~ j) => Each (Array i a) (Array j b) a b where+  each f arr = array (bounds arr) <$> traverse (\(i,a) -> (,) i <$> f a) (IArray.assocs arr)+  {-# INLINE each #-}++-- | @'each' :: ('Ix' i, 'IArray' 'UArray' a, 'IArray' 'UArray' b) => 'Traversal' ('Array' i a) ('Array' i b) a b@+instance (Ix i, IArray UArray a, IArray UArray b, i ~ j) => Each (UArray i a) (UArray j b) a b where+  each f arr = array (bounds arr) <$> traverse (\(i,a) -> (,) i <$> f a) (IArray.assocs arr)+  {-# INLINE each #-}++-------------------------------------------------------------------------------+-- strict+-------------------------------------------------------------------------------++-- | @since 4.20+instance (a ~ a', b ~ b') => Each (S.Either a a') (S.Either b b') a b where+    each f (S.Left x)  = S.Left <$> f x+    each f (S.Right x) = S.Right <$> f x+    {-# INLINE each #-}++-- | @since 4.20+instance (a~a', b~b') => Each (S.Pair a a') (S.Pair b b') a b where+    each f (a S.:!: b) = (S.:!:) <$> f a <*> f b+    {-# INLINE each #-}++-- | @since 4.20+instance Each (S.Maybe a) (S.Maybe b) a b++-- | @since 4.20+instance (a ~ a', b ~ b') => Each (S.These a a') (S.These b b') a b where+    each f (S.This a)    = S.This <$> f a+    each f (S.That b)    = S.That <$> f b+    each f (S.These a b) = S.These <$> f a <*> f b++-------------------------------------------------------------------------------+-- these+-------------------------------------------------------------------------------++-- | @since 4.20+instance (a ~ a', b ~ b') => Each (These a a') (These b b') a b where+    each f (This a)    = This <$> f a+    each f (That b)    = That <$> f b+    each f (These a b) = These <$> f a <*> f b
+ src/Control/Lens/Empty.hs view
@@ -0,0 +1,200 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE DefaultSignatures #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-}++#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-}+#endif++-------------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Empty+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  non-portable+--+-------------------------------------------------------------------------------+module Control.Lens.Empty+  (+    AsEmpty(..)+  , pattern Empty+  ) where++import Prelude ()++import Control.Lens.Iso+import Control.Lens.Fold+import Control.Lens.Prism+import Control.Lens.Internal.Prelude as Prelude+import Control.Lens.Review+import qualified Data.ByteString as StrictB+import qualified Data.ByteString.Lazy as LazyB+import qualified Data.HashMap.Lazy as HashMap+import Data.HashMap.Lazy (HashMap)+import qualified Data.HashSet as HashSet+import Data.HashSet (HashSet)+import qualified Data.IntMap as IntMap+import Data.IntMap (IntMap)+import qualified Data.IntSet as IntSet+import Data.IntSet (IntSet)+import Data.Monoid+import qualified Data.Map as Map+import Data.Map (Map)+import Data.Maybe+import qualified Data.Sequence as Seq+import qualified Data.Set as Set+import Data.Set (Set)+import qualified Data.Text as StrictT+import qualified Data.Text.Lazy as LazyT+import qualified Data.Vector as Vector+import qualified Data.Vector.Unboxed as Unboxed+import Data.Vector.Unboxed (Unbox)+import qualified Data.Vector.Storable as Storable+import qualified Data.Vector.Primitive as Prim+#if MIN_VERSION_vector(0,13,2)+import qualified Data.Vector.Strict as VectorStrict+#endif+import Foreign.Storable (Storable)++#if !defined(mingw32_HOST_OS) && !defined(ghcjs_HOST_OS)+import GHC.Event+#endif++-- $setup+-- >>> import Control.Lens++class AsEmpty a where+  -- |+  --+  -- >>> isn't _Empty [1,2,3]+  -- True+  _Empty :: Prism' a ()+  default _Empty :: (Monoid a, Eq a) => Prism' a ()+  _Empty = only mempty+  {-# INLINE _Empty #-}++pattern Empty :: AsEmpty s => s+pattern Empty <- (has _Empty -> True) where+  Empty = review _Empty ()++{- Default Monoid instances -}+instance AsEmpty Ordering+instance AsEmpty ()+instance AsEmpty Any+instance AsEmpty All+#if !defined(mingw32_HOST_OS) && !defined(ghcjs_HOST_OS)+instance AsEmpty Event+#endif+instance (Eq a, Num a) => AsEmpty (Product a)+instance (Eq a, Num a) => AsEmpty (Sum a)++instance AsEmpty (Maybe a) where+  _Empty = _Nothing+  {-# INLINE _Empty #-}++instance AsEmpty (Last a) where+  _Empty = nearly (Last Nothing) (isNothing .# getLast)+  {-# INLINE _Empty #-}++instance AsEmpty (First a) where+  _Empty = nearly (First Nothing) (isNothing .# getFirst)+  {-# INLINE _Empty #-}++instance AsEmpty a => AsEmpty (Dual a) where+  _Empty = iso getDual Dual . _Empty+  {-# INLINE _Empty #-}++instance (AsEmpty a, AsEmpty b) => AsEmpty (a,b) where+  _Empty = prism' (\() -> (_Empty # (), _Empty # ())) $ \(s,s') -> case _Empty Left s of+    Left () -> case _Empty Left s' of+      Left () -> Just ()+      _       -> Nothing+    _         -> Nothing+  {-# INLINE _Empty #-}++instance (AsEmpty a, AsEmpty b, AsEmpty c) => AsEmpty (a,b,c) where+  _Empty = prism' (\() -> (_Empty # (), _Empty # (), _Empty # ())) $ \(s,s',s'') -> case _Empty Left s of+    Left () -> case _Empty Left s' of+      Left () -> case _Empty Left s'' of+        Left () -> Just ()+        Right _ -> Nothing+      Right _   -> Nothing+    Right _     -> Nothing+  {-# INLINE _Empty #-}++instance AsEmpty [a] where+  _Empty = nearly [] Prelude.null+  {-# INLINE _Empty #-}++instance AsEmpty (ZipList a) where+  _Empty = nearly (ZipList []) (Prelude.null . getZipList)+  {-# INLINE _Empty #-}++instance AsEmpty (Map k a) where+  _Empty = nearly Map.empty Map.null+  {-# INLINE _Empty #-}++instance AsEmpty (HashMap k a) where+  _Empty = nearly HashMap.empty HashMap.null+  {-# INLINE _Empty #-}++instance AsEmpty (IntMap a) where+  _Empty = nearly IntMap.empty IntMap.null+  {-# INLINE _Empty #-}++instance AsEmpty (Set a) where+  _Empty = nearly Set.empty Set.null+  {-# INLINE _Empty #-}++instance AsEmpty (HashSet a) where+  _Empty = nearly HashSet.empty HashSet.null+  {-# INLINE _Empty #-}++instance AsEmpty IntSet where+  _Empty = nearly IntSet.empty IntSet.null+  {-# INLINE _Empty #-}++instance AsEmpty (Vector.Vector a) where+  _Empty = nearly Vector.empty Vector.null+  {-# INLINE _Empty #-}++instance Unbox a => AsEmpty (Unboxed.Vector a) where+  _Empty = nearly Unboxed.empty Unboxed.null+  {-# INLINE _Empty #-}++instance Prim.Prim a => AsEmpty (Prim.Vector a) where+  _Empty = nearly Prim.empty Prim.null+  {-# INLINE _Empty #-}++instance Storable a => AsEmpty (Storable.Vector a) where+  _Empty = nearly Storable.empty Storable.null+  {-# INLINE _Empty #-}++#if MIN_VERSION_vector(0,13,2)+instance AsEmpty (VectorStrict.Vector a) where+  _Empty = nearly VectorStrict.empty VectorStrict.null+  {-# INLINE _Empty #-}+#endif++instance AsEmpty (Seq.Seq a) where+  _Empty = nearly Seq.empty Seq.null+  {-# INLINE _Empty #-}++instance AsEmpty StrictB.ByteString where+  _Empty = nearly StrictB.empty StrictB.null+  {-# INLINE _Empty #-}++instance AsEmpty LazyB.ByteString where+  _Empty = nearly LazyB.empty LazyB.null+  {-# INLINE _Empty #-}++instance AsEmpty StrictT.Text where+  _Empty = nearly StrictT.empty StrictT.null+  {-# INLINE _Empty #-}++instance AsEmpty LazyT.Text where+  _Empty = nearly LazyT.empty LazyT.null+  {-# INLINE _Empty #-}
+ src/Control/Lens/Equality.hs view
@@ -0,0 +1,160 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE Trustworthy #-}++#if __GLASGOW_HASKELL__ >= 806+{-# LANGUAGE PolyKinds #-}+#else+{-# LANGUAGE TypeInType #-}+#endif++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Equality+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  Rank2Types+--+----------------------------------------------------------------------------+module Control.Lens.Equality+  (+  -- * Type Equality+    Equality, Equality'+  , AnEquality, AnEquality'+  , (:~:)(..)+  , runEq+  , substEq+  , mapEq+  , fromEq+  , simply+  -- * The Trivial Equality+  , simple+  -- * 'Iso'-like functions+  , equality+  , equality'+  , withEquality+  , underEquality+  , overEquality+  , fromLeibniz+  , fromLeibniz'+  , cloneEquality+  -- * Implementation Details+  , Identical(..)+  ) where++import Control.Lens.Type+import Data.Proxy (Proxy)+import Data.Type.Equality ((:~:)(..))+import GHC.Exts (TYPE)+import Data.Kind (Type)++-- $setup+-- >>> import Control.Lens++#include "lens-common.h"++-----------------------------------------------------------------------------+-- Equality+-----------------------------------------------------------------------------++-- | Provides witness that @(s ~ a, b ~ t)@ holds.+data Identical a b s t where+  Identical :: Identical a b a b++-- | When you see this as an argument to a function, it expects an 'Equality'.+type AnEquality s t a b = Identical a (Proxy b) a (Proxy b) -> Identical a (Proxy b) s (Proxy t)++-- | A 'Simple' 'AnEquality'.+type AnEquality' s a = AnEquality s s a a++-- | Extract a witness of type 'Equality'.+runEq :: AnEquality s t a b -> Identical s t a b+runEq l = case l Identical of Identical -> Identical+{-# INLINE runEq #-}++-- | Substituting types with 'Equality'.+substEq :: forall s t a b rep (r :: TYPE rep).+           AnEquality s t a b -> ((s ~ a, t ~ b) => r) -> r+substEq l = case runEq l of+  Identical -> \r -> r+{-# INLINE substEq #-}++-- | We can use 'Equality' to do substitution into anything.+mapEq :: forall k1 k2 (s :: k1) (t :: k2) (a :: k1) (b :: k2) (f :: k1 -> Type) . AnEquality s t a b -> f s -> f a+mapEq l r = substEq l r+{-# INLINE mapEq #-}++-- | 'Equality' is symmetric.+fromEq :: AnEquality s t a b -> Equality b a t s+fromEq l = substEq l id+{-# INLINE fromEq #-}++-- | This is an adverb that can be used to modify many other 'Lens' combinators to make them require+-- simple lenses, simple traversals, simple prisms or simple isos as input.+simply :: forall p f s a rep (r :: TYPE rep).+  (Optic' p f s a -> r) -> Optic' p f s a -> r+simply = id+{-# INLINE simply #-}++-- | Composition with this isomorphism is occasionally useful when your 'Lens',+-- 'Control.Lens.Traversal.Traversal' or 'Iso' has a constraint on an unused+-- argument to force that argument to agree with the+-- type of a used argument and avoid @ScopedTypeVariables@ or other ugliness.+simple :: Equality' a a+simple = id+{-# INLINE simple #-}++cloneEquality :: AnEquality s t a b -> Equality s t a b+cloneEquality an = substEq an id+{-# INLINE cloneEquality #-}++-- | Construct an 'Equality' from explicit equality evidence.+equality :: s :~: a -> b :~: t -> Equality s t a b+equality Refl Refl = id+{-# INLINE equality #-}++-- | A 'Simple' version of 'equality'+equality' :: a :~: b -> Equality' a b+equality' Refl = id+{-# INLINE equality' #-}++-- | Recover a "profunctor lens" form of equality. Reverses 'fromLeibniz'.+overEquality :: AnEquality s t a b -> p a b -> p s t+overEquality an = substEq an id+{-# INLINE overEquality #-}++-- | The opposite of working 'overEquality' is working 'underEquality'.+underEquality :: AnEquality s t a b -> p t s -> p b a+underEquality an = substEq an id+{-# INLINE underEquality #-}++-- | Convert a "profunctor lens" form of equality to an equality. Reverses+-- 'overEquality'.+--+-- The type should be understood as+--+-- @fromLeibniz :: (forall p. p a b -> p s t) -> Equality s t a b@+fromLeibniz :: (Identical a b a b -> Identical a b s t) -> Equality s t a b+fromLeibniz f = case f Identical of Identical -> id+{-# INLINE fromLeibniz #-}++-- | Convert Leibniz equality to equality. Reverses 'mapEq' in 'Simple' cases.+--+-- The type should be understood as+--+-- @fromLeibniz' :: (forall f. f s -> f a) -> Equality' s a@+fromLeibniz' :: (s :~: s -> s :~: a) -> Equality' s a+fromLeibniz' f = case f Refl of Refl -> id+{-# INLINE fromLeibniz' #-}++-- | A version of 'substEq' that provides explicit, rather than implicit,+-- equality evidence.+withEquality :: forall s t a b rep (r :: TYPE rep).+   AnEquality s t a b -> (s :~: a -> b :~: t -> r) -> r+withEquality an = substEq an (\f -> f Refl Refl)+{-# INLINE withEquality #-}
+ src/Control/Lens/Extras.hs view
@@ -0,0 +1,34 @@+-----------------------------------------------------------------------------+-- |+-- Module      :  Data.List.Lens+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  portable+--+-- A few extra names that didn't make it into Control.Lens.+--+----------------------------------------------------------------------------+module Control.Lens.Extras+  ( is+  , module Data.Data.Lens+  ) where++import Control.Lens+import Data.Data.Lens++-- $setup+-- >>> import Control.Lens+-- >>> import Numeric.Lens (hex)++-- | Check to see if this t'Prism' matches.+--+-- >>> is _Left (Right 12)+-- False+--+-- >>> is hex "3f79"+-- True+is :: APrism s t a b -> s -> Bool+is k = not . isn't k+{-# INLINE is #-}
src/Control/Lens/Fold.hs view
@@ -1,973 +1,2807 @@-{-# LANGUAGE Rank2Types #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE LiberalTypeSynonyms #-}-{-# LANGUAGE UndecidableInstances #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FunctionalDependencies #-}-------------------------------------------------------------------------------- |--- Module      :  Control.Lens.Fold--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  Rank2Types------ A @'Fold' a c@ is a generalization of something 'Foldable'. It allows--- you to extract multiple results from a container. A 'Foldable' container--- can be characterized by the behavior of--- @foldMap :: ('Foldable' t, 'Monoid' m) => (c -> m) -> t c -> m@.--- Since we want to be able to work with monomorphic containers, we could--- generalize this signature to @forall m. 'Monoid' m => (c -> m) -> a -> m@,--- and then decorate it with 'Accessor' to obtain------ @type 'Fold' a c = forall m. 'Monoid' m => 'Getting' m a a c c@------ Every 'Getter' is a valid 'Fold' that simply doesn't use the 'Monoid'--- it is passed.------ In practice the type we use is slightly more complicated to allow for--- better error messages and for it to be transformed by certain--- 'Applicative' transformers.------ Everything you can do with a 'Foldable' container, you can with with a 'Fold' and there are--- combinators that generalize the usual 'Foldable' operations here.------------------------------------------------------------------------------module Control.Lens.Fold-  (-  -- * Folds-    Fold-  , (^?), (^..)-  -- ** Building Folds-  --, folds-  , folding-  , folded-  , unfolded-  , iterated-  , filtered-  , backwards-  , repeated-  , replicated-  , cycled-  , takingWhile-  , droppingWhile-  -- ** Folding-  , foldMapOf, foldOf-  , foldrOf, foldlOf-  , toListOf-  , anyOf, allOf-  , andOf, orOf-  , productOf, sumOf-  , traverseOf_, forOf_, sequenceAOf_-  , mapMOf_, forMOf_, sequenceOf_-  , asumOf, msumOf-  , concatMapOf, concatOf-  , elemOf, notElemOf-  , lengthOf-  , nullOf-  , headOf, lastOf-  , maximumOf, minimumOf-  , maximumByOf, minimumByOf-  , findOf-  , foldrOf', foldlOf'-  , foldr1Of, foldl1Of-  , foldrMOf, foldlMOf-  -- * Storing Folds-  , ReifiedFold(..)-  ) where--import Control.Applicative as Applicative-import Control.Applicative.Backwards-import Control.Lens.Getter-import Control.Lens.Internal-import Control.Lens.Type-import Control.Monad-import Data.Foldable as Foldable-import Data.Maybe-import Data.Monoid---- $setup--- >>> import Control.Lens--infixl 8 ^?, ^..------------------------------- Folds------------------------------- | A 'Fold' describes how to retrieve multiple values in a way that can be composed--- with other lens-like constructions.------ A @'Fold' a c@ provides a structure with operations very similar to those of the 'Foldable'--- typeclass, see 'foldMapOf' and the other 'Fold' combinators.------ By convention, if there exists a 'foo' method that expects a @'Foldable' (f c)@, then there should be a--- @fooOf@ method that takes a @'Fold' a c@ and a value of type @a@.------ A 'Getter' is a legal 'Fold' that just ignores the supplied 'Monoid'------ Unlike a 'Control.Lens.Traversal.Traversal' a 'Fold' is read-only. Since a 'Fold' cannot be used to write back--- there are no lens laws that apply.-type Fold a c = forall f. (Gettable f, Applicative f) => (c -> f c) -> a -> f a----- | Obtain a 'Fold' by lifting an operation that returns a foldable result.------ This can be useful to lift operations from @Data.List@ and elsewhere into a 'Fold'.-folding :: (Foldable f, Applicative g, Gettable g) => (a -> f c) -> LensLike g a b c d-folding afc cgd = coerce . traverse_ cgd . afc-{-# INLINE folding #-}---- | Obtain a 'Fold' from any 'Foldable'.-folded :: Foldable f => Fold (f c) c-folded f = coerce . getFolding . foldMap (Folding . f)-{-# INLINE folded #-}---- | Fold by repeating the input forever.------ @'repeat' ≡ 'toListOf' 'repeated'@-repeated :: Fold a a-repeated f a = as where as = f a *> as---- | A fold that replicates its input @n@ times.------ @'replicate' n ≡ 'toListOf' ('replicated' n)@-replicated :: Int -> Fold a a-replicated n0 f a = go n0 where-  m = f a-  go 0 = noEffect-  go n = m *> go (n - 1)-{-# INLINE replicated #-}---- | Transform a fold into a fold that loops over its elements over and over.------ >>> take 6 $ toListOf (cycled traverse) [1,2,3]--- [1,2,3,1,2,3]-cycled :: (Applicative f, Gettable f) => LensLike f a b c d -> LensLike f a b c d-cycled l f a = as where as = l f a *> as---- | Build a fold that unfolds its values from a seed.------ @'Prelude.unfoldr' ≡ 'toListOf' . 'unfolded'@-unfolded :: (b -> Maybe (a, b)) -> Fold b a-unfolded f g b0 = go b0 where-  go b = case f b of-    Just (a, b') -> g a *> go b'-    Nothing      -> noEffect-{-# INLINE unfolded #-}---- | @x ^. 'iterated' f@ Return an infinite fold of repeated applications of @f@ to @x@.------ @'toListOf' ('iterated' f) a ≡ 'iterate' f a@-iterated :: (a -> a) -> Fold a a-iterated f g a0 = go a0 where-  go a = g a *> go (f a)-{-# INLINE iterated #-}---- | Obtain a 'Fold' by filtering a 'Lens', 'Control.Lens.Iso.Iso', 'Getter', 'Fold' or 'Control.Lens.Traversal.Traversal'.-filtered :: (Gettable f, Applicative f) => (c -> Bool) -> LensLike f a b c d -> LensLike f a b c d-filtered p l f = l $ \c -> if p c then f c-                                  else noEffect-{-# INLINE filtered #-}---- | This allows you to traverse the elements of a 'Control.Lens.Traversal.Traversal' or 'Fold' in the opposite order.------ Note: 'backwards' should have no impact on a 'Getter' 'Setter', 'Lens' or 'Control.Lens.Iso.Iso'.------ To change the direction of an 'Control.Lens.Iso.Iso', use 'from'.-backwards :: LensLike (Backwards f) a b c d -> LensLike f a b c d-backwards l f = forwards . l (Backwards . f)-{-# INLINE backwards #-}---- | Obtain a 'Fold' by taking elements from another 'Fold', 'Lens', 'Control.Lens.Iso.Iso', 'Getter' or 'Control.Lens.Traversal.Traversal' while a predicate holds.------ @'takeWhile' p ≡ 'toListOf' ('takingWhile' p 'folded')@------ >>> toListOf (takingWhile (<=3) folded) [1..]--- [1,2,3]-takingWhile :: (Gettable f, Applicative f)-            => (c -> Bool)-            -> Getting (Endo (f a)) a a c c-            -> LensLike f a a c c-takingWhile p l f = foldrOf l (\a r -> if p a then f a *> r else noEffect) noEffect-{-# INLINE takingWhile #-}----- | Obtain a 'Fold' by dropping elements from another 'Fold', 'Lens', 'Control.Lens.Iso.Iso', 'Getter' or 'Control.Lens.Traversal.Traversal' while a predicate holds.------ @'dropWhile' p ≡ 'toListOf' ('droppingWhile' p 'folded')@------ >>> toListOf (droppingWhile (<=3) folded) [1..6]--- [4,5,6]-droppingWhile :: (Gettable f, Applicative f)-              => (c -> Bool)-              -> Getting (Endo (f a)) a a c c-              -> LensLike f a a c c-droppingWhile p l f = foldrOf l (\a r -> if p a then r else f a *> r) noEffect-{-# INLINE droppingWhile #-}------------------------------- Fold/Getter combinators------------------------------- |--- @'Data.Foldable.foldMap' = 'foldMapOf' 'folded'@------ @'foldMapOf' ≡ 'views'@------ @--- 'foldMapOf' ::             'Getter' a c           -> (c -> r) -> a -> r--- 'foldMapOf' :: 'Monoid' r => 'Fold' a c             -> (c -> r) -> a -> r--- 'foldMapOf' ::             'Simple' 'Lens' a c      -> (c -> r) -> a -> r--- 'foldMapOf' ::             'Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> r) -> a -> r--- 'foldMapOf' :: 'Monoid' r => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> r) -> a -> r--- @-foldMapOf :: Getting r a b c d -> (c -> r) -> a -> r-foldMapOf l f = runAccessor . l (Accessor . f)-{-# INLINE foldMapOf #-}---- |--- @'Data.Foldable.fold' = 'foldOf' 'folded'@------ @'foldOf' ≡ 'view'@------ @--- 'foldOf' ::             'Getter' a m           -> a -> m--- 'foldOf' :: 'Monoid' m => 'Fold' a m             -> a -> m--- 'foldOf' ::             'Simple' 'Lens' a m      -> a -> m--- 'foldOf' ::             'Simple' 'Control.Lens.Iso.Iso' a m       -> a -> m--- 'foldOf' :: 'Monoid' m => 'Simple' 'Control.Lens.Traversal.Traversal' a m -> a -> m--- @-foldOf :: Getting c a b c d -> a -> c-foldOf l = runAccessor . l Accessor-{-# INLINE foldOf #-}---- |--- Right-associative fold of parts of a structure that are viewed through a 'Lens', 'Getter', 'Fold' or 'Control.Lens.Traversal.Traversal'.------ @'Data.Foldable.foldr' ≡ 'foldrOf' 'folded'@------ @--- 'foldrOf' :: 'Getter' a c           -> (c -> e -> e) -> e -> a -> e--- 'foldrOf' :: 'Fold' a c             -> (c -> e -> e) -> e -> a -> e--- 'foldrOf' :: 'Simple' 'Lens' a c      -> (c -> e -> e) -> e -> a -> e--- 'foldrOf' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> e -> e) -> e -> a -> e--- 'foldrOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> e -> e) -> e -> a -> e--- @-foldrOf :: Getting (Endo e) a b c d -> (c -> e -> e) -> e -> a -> e-foldrOf l f z t = appEndo (foldMapOf l (Endo . f) t) z-{-# INLINE foldrOf #-}---- |--- Left-associative fold of the parts of a structure that are viewed through a 'Lens', 'Getter', 'Fold' or 'Control.Lens.Traversal.Traversal'.------ @'Data.Foldable.foldl' ≡ 'foldlOf' 'folded'@------ @--- 'foldlOf' :: 'Getter' a c           -> (e -> c -> e) -> e -> a -> e--- 'foldlOf' :: 'Fold' a c             -> (e -> c -> e) -> e -> a -> e--- 'foldlOf' :: 'Simple' 'Lens' a c      -> (e -> c -> e) -> e -> a -> e--- 'foldlOf' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> (e -> c -> e) -> e -> a -> e--- 'foldlOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (e -> c -> e) -> e -> a -> e--- @-foldlOf :: Getting (Dual (Endo e)) a b c d -> (e -> c -> e) -> e -> a -> e-foldlOf l f z t = appEndo (getDual (foldMapOf l (Dual . Endo . flip f) t)) z-{-# INLINE foldlOf #-}---- | Extract a list of the targets of a 'Fold'. See also ('^..').------ @--- 'Data.Foldable.toList' ≡ 'toListOf' 'folded'--- ('^..') ≡ 'flip' 'toListOf'--- @---- >>> toListOf both ("hello","world")--- ["hello","world"]------ @--- 'toListOf' :: 'Getter' a c           -> a -> [c]--- 'toListOf' :: 'Fold' a c             -> a -> [c]--- 'toListOf' :: 'Simple' 'Lens' a c      -> a -> [c]--- 'toListOf' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> a -> [c]--- 'toListOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> [c]--- @-toListOf :: Getting [c] a b c d -> a -> [c]-toListOf l = foldMapOf l return-{-# INLINE toListOf #-}---- |------ A convenient infix (flipped) version of 'toListOf'.------ >>> [[1,2],[3]]^..traverse.traverse--- [1,2,3]------ >>> (1,2)^..both--- [1,2]------ @--- 'Data.Foldable.toList' xs ≡ xs '^..' 'folded'--- ('^..') ≡ 'flip' 'toListOf'--- @------ @--- ('^..') :: a -> 'Getter' a c           -> [c]--- ('^..') :: a -> 'Fold' a c             -> [c]--- ('^..') :: a -> 'Simple' 'Lens' a c      -> [c]--- ('^..') :: a -> 'Simple' 'Control.Lens.Iso.Iso' a c       -> [c]--- ('^..') :: a -> 'Simple' 'Control.Lens.Traversal.Traversal' a c -> [c]--- @-(^..) :: a -> Getting [c] a b c d -> [c]-a ^.. l = foldMapOf l return a---- | Returns 'True' if every target of a 'Fold' is 'True'.------ >>> andOf both (True,False)--- False--- >>> andOf both (True,True)--- True------ @'Data.Foldable.and' ≡ 'andOf' 'folded'@------ @--- 'andOf' :: 'Getter' a 'Bool'           -> a -> 'Bool'--- 'andOf' :: 'Fold' a 'Bool'             -> a -> 'Bool'--- 'andOf' :: 'Simple' 'Lens' a 'Bool'      -> a -> 'Bool'--- 'andOf' :: 'Simple' 'Control.Lens.Iso.Iso' a 'Bool'       -> a -> 'Bool'--- 'andOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a 'Bool' -> a -> 'Bool'--- @-andOf :: Getting All a b Bool d -> a -> Bool-andOf l = getAll . foldMapOf l All-{-# INLINE andOf #-}---- | Returns 'True' if any target of a 'Fold' is 'True'.------ >>> orOf both (True,False)--- True--- >>> orOf both (False,False)--- False------ @'Data.Foldable.or' ≡ 'orOf' 'folded'@------ @--- 'orOf' :: 'Getter' a 'Bool'           -> a -> 'Bool'--- 'orOf' :: 'Fold' a 'Bool'             -> a -> 'Bool'--- 'orOf' :: 'Simple' 'Lens' a 'Bool'      -> a -> 'Bool'--- 'orOf' :: 'Simple' 'Control.Lens.Iso.Iso' a 'Bool'       -> a -> 'Bool'--- 'orOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a 'Bool' -> a -> 'Bool'--- @-orOf :: Getting Any a b Bool d -> a -> Bool-orOf l = getAny . foldMapOf l Any-{-# INLINE orOf #-}---- | Returns 'True' if any target of a 'Fold' satisfies a predicate.------ >>> anyOf both (=='x') ('x','y')--- True--- >>> import Data.Data.Lens--- >>> anyOf biplate (== "world") (((),2::Int),"hello",("world",11))--- True------ @'Data.Foldable.any' ≡ 'anyOf' 'folded'@------ @--- 'anyOf' :: 'Getter' a c               -> (c -> 'Bool') -> a -> 'Bool'--- 'anyOf' :: 'Fold' a c                 -> (c -> 'Bool') -> a -> 'Bool'--- 'anyOf' :: 'Simple' 'Lens' a b c d      -> (c -> 'Bool') -> a -> 'Bool'--- 'anyOf' :: 'Simple' 'Control.Lens.Iso.Iso' a b c d       -> (c -> 'Bool') -> a -> 'Bool'--- 'anyOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a b c d -> (c -> 'Bool') -> a -> 'Bool'--- @-anyOf :: Getting Any a b c d -> (c -> Bool) -> a -> Bool-anyOf l f = getAny . foldMapOf l (Any . f)-{-# INLINE anyOf #-}---- | Returns 'True' if every target of a 'Fold' satisfies a predicate.------ >>> allOf both (>=3) (4,5)--- True--- >>> allOf folded (>=2) [1..10]--- False------ @'Data.Foldable.all' ≡ 'allOf' 'folded'@------ @--- 'allOf' :: 'Getter' a c           -> (c -> 'Bool') -> a -> 'Bool'--- 'allOf' :: 'Fold' a c             -> (c -> 'Bool') -> a -> 'Bool'--- 'allOf' :: 'Simple' 'Lens' a c      -> (c -> 'Bool') -> a -> 'Bool'--- 'allOf' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> 'Bool') -> a -> 'Bool'--- 'allOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> 'Bool') -> a -> 'Bool'--- @-allOf :: Getting All a b c d -> (c -> Bool) -> a -> Bool-allOf l f = getAll . foldMapOf l (All . f)-{-# INLINE allOf #-}---- | Calculate the product of every number targeted by a 'Fold'------ >>> productOf both (4,5)--- 20--- >>> productOf folded [1,2,3,4,5]--- 120------ @'Data.Foldable.product' ≡ 'productOf' 'folded'@------ @--- 'productOf' ::          'Getter' a c           -> a -> c--- 'productOf' :: 'Num' c => 'Fold' a c             -> a -> c--- 'productOf' ::          'Simple' 'Lens' a c      -> a -> c--- 'productOf' ::          'Simple' 'Control.Lens.Iso.Iso' a c       -> a -> c--- 'productOf' :: 'Num' c => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> c--- @-productOf :: Getting (Product c) a b c d -> a -> c-productOf l = getProduct . foldMapOf l Product-{-# INLINE productOf #-}---- | Calculate the sum of every number targeted by a 'Fold'.------ >>> sumOf both (5,6)--- 11--- >>> sumOf folded [1,2,3,4]--- 10--- >>> sumOf (folded.both) [(1,2),(3,4)]--- 10--- >>> import Data.Data.Lens--- >>> sumOf biplate [(1::Int,[]),(2,[(3::Int,4::Int)])] :: Int--- 10------ @'Data.Foldable.sum' ≡ 'sumOf' 'folded'@------ @--- 'sumOf' '_1' :: (a, b) -> a--- 'sumOf' ('folded' . '_1') :: ('Foldable' f, 'Num' a) => f (a, b) -> a--- @------ @--- 'sumOf' ::          'Getter' a c           -> a -> c--- 'sumOf' :: 'Num' c => 'Fold' a c             -> a -> c--- 'sumOf' ::          'Simple' 'Lens' a c      -> a -> c--- 'sumOf' ::          'Simple' 'Control.Lens.Iso.Iso' a c       -> a -> c--- 'sumOf' :: 'Num' c => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> c--- @-sumOf :: Getting (Sum c) a b c d -> a -> c-sumOf l = getSum . foldMapOf l Sum-{-# INLINE sumOf #-}---- | Traverse over all of the targets of a 'Fold' (or 'Getter'), computing an 'Applicative' (or 'Functor') -based answer,--- but unlike 'Control.Lens.Traversal.traverseOf' do not construct a new structure. 'traverseOf_' generalizes--- 'Data.Foldable.traverse_' to work over any 'Fold'.------ When passed a 'Getter', 'traverseOf_' can work over any 'Functor', but when passed a 'Fold', 'traverseOf_' requires--- an 'Applicative'.------ >>> traverseOf_ both putStrLn ("hello","world")--- hello--- world------ @'Data.Foldable.traverse_' ≡ 'traverseOf_' 'folded'@------ @--- 'traverseOf_' '_2' :: 'Functor' f => (c -> f e) -> (c1, c) -> f ()--- 'traverseOf_' 'Data.Either.Lens.traverseLeft' :: 'Applicative' f => (a -> f b) -> 'Either' a c -> f ()--- @------ The rather specific signature of 'traverseOf_' allows it to be used as if the signature was any of:------ @--- 'traverseOf_' :: 'Functor' f     => 'Getter' a c           -> (c -> f e) -> a -> f ()--- 'traverseOf_' :: 'Applicative' f => 'Fold' a c             -> (c -> f e) -> a -> f ()--- 'traverseOf_' :: 'Functor' f     => 'Simple' 'Lens' a c      -> (c -> f e) -> a -> f ()--- 'traverseOf_' :: 'Functor' f     => 'Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> f e) -> a -> f ()--- 'traverseOf_' :: 'Applicative' f => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> f e) -> a -> f ()--- @-traverseOf_ :: Functor f => Getting (Traversed f) a b c d -> (c -> f e) -> a -> f ()-traverseOf_ l f = getTraversed . foldMapOf l (Traversed . void . f)-{-# INLINE traverseOf_ #-}---- | Traverse over all of the targets of a 'Fold' (or 'Getter'), computing an 'Applicative' (or 'Functor') -based answer,--- but unlike 'Control.Lens.Traversal.forOf' do not construct a new structure. 'forOf_' generalizes--- 'Data.Foldable.for_' to work over any 'Fold'.------ When passed a 'Getter', 'forOf_' can work over any 'Functor', but when passed a 'Fold', 'forOf_' requires--- an 'Applicative'.------ @'for_' ≡ 'forOf_' 'folded'@------ The rather specific signature of 'forOf_' allows it to be used as if the signature was any of:------ @--- 'forOf_' :: 'Functor' f     => 'Getter' a c           -> a -> (c -> f e) -> f ()--- 'forOf_' :: 'Applicative' f => 'Fold' a c             -> a -> (c -> f e) -> f ()--- 'forOf_' :: 'Functor' f     => 'Simple' 'Lens' a c      -> a -> (c -> f e) -> f ()--- 'forOf_' :: 'Functor' f     => 'Simple' 'Control.Lens.Iso.Iso' a c       -> a -> (c -> f e) -> f ()--- 'forOf_' :: 'Applicative' f => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> (c -> f e) -> f ()--- @-forOf_ :: Functor f => Getting (Traversed f) a b c d -> a -> (c -> f e) -> f ()-forOf_ = flip . traverseOf_-{-# INLINE forOf_ #-}---- | Evaluate each action in observed by a 'Fold' on a structure from left to right, ignoring the results.------ @'sequenceA_' ≡ 'sequenceAOf_' 'folded'@------ @--- 'sequenceAOf_' :: 'Functor' f     => 'Getter' a (f ())           -> a -> f ()--- 'sequenceAOf_' :: 'Applicative' f => 'Fold' a (f ())             -> a -> f ()--- 'sequenceAOf_' :: 'Functor' f     => 'Simple' 'Lens' a (f ())      -> a -> f ()--- 'sequenceAOf_' :: 'Functor' f     => 'Simple' 'Iso' a (f ())       -> a -> f ()--- 'sequenceAOf_' :: 'Applicative' f => 'Simple' 'Control.Lens.Traversal.Traversal' a (f ()) -> a -> f ()--- @-sequenceAOf_ :: Functor f => Getting (Traversed f) a b (f ()) d -> a -> f ()-sequenceAOf_ l = getTraversed . foldMapOf l (Traversed . void)-{-# INLINE sequenceAOf_ #-}---- | Map each target of a 'Fold' on a structure to a monadic action, evaluate these actions from left to right, and ignore the results.------ @'Data.Foldable.mapM_' ≡ 'mapMOf_' 'folded'@------ @--- 'mapMOf_' :: 'Monad' m => 'Getter' a c           -> (c -> m e) -> a -> m ()--- 'mapMOf_' :: 'Monad' m => 'Fold' a c             -> (c -> m e) -> a -> m ()--- 'mapMOf_' :: 'Monad' m => 'Simple' 'Lens' a c      -> (c -> m e) -> a -> m ()--- 'mapMOf_' :: 'Monad' m => 'Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> m e) -> a -> m ()--- 'mapMOf_' :: 'Monad' m => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> m e) -> a -> m ()--- @-mapMOf_ :: Monad m => Getting (Sequenced m) a b c d -> (c -> m e) -> a -> m ()-mapMOf_ l f = getSequenced . foldMapOf l (Sequenced . liftM skip . f)-{-# INLINE mapMOf_ #-}--skip :: a -> ()-skip _ = ()-{-# INLINE skip #-}---- | 'forMOf_' is 'mapMOf_' with two of its arguments flipped.------ @'Data.Foldable.forM_' ≡ 'forMOf_' 'folded'@------ @--- 'forMOf_' :: 'Monad' m => 'Getter' a c           -> a -> (c -> m e) -> m ()--- 'forMOf_' :: 'Monad' m => 'Fold' a c             -> a -> (c -> m e) -> m ()--- 'forMOf_' :: 'Monad' m => 'Simple' 'Lens' a c      -> a -> (c -> m e) -> m ()--- 'forMOf_' :: 'Monad' m => 'Simple' 'Control.Lens.Iso.Iso' a c       -> a -> (c -> m e) -> m ()--- 'forMOf_' :: 'Monad' m => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> (c -> m e) -> m ()--- @-forMOf_ :: Monad m => Getting (Sequenced m) a b c d -> a -> (c -> m e) -> m ()-forMOf_ = flip . mapMOf_-{-# INLINE forMOf_ #-}---- | Evaluate each monadic action referenced by a 'Fold' on the structure from left to right, and ignore the results.------ @'Data.Foldable.sequence_' ≡ 'sequenceOf_' 'folded'@------ @--- 'sequenceOf_' :: 'Monad' m => 'Getter' a (m b)           -> a -> m ()--- 'sequenceOf_' :: 'Monad' m => 'Fold' a (m b)             -> a -> m ()--- 'sequenceOf_' :: 'Monad' m => 'Simple' 'Lens' a (m b)      -> a -> m ()--- 'sequenceOf_' :: 'Monad' m => 'Simple' 'Control.Lens.Iso.Iso' a (m b)       -> a -> m ()--- 'sequenceOf_' :: 'Monad' m => 'Simple' 'Control.Lens.Traversal.Traversal' a (m b) -> a -> m ()--- @-sequenceOf_ :: Monad m => Getting (Sequenced m) a b (m c) d -> a -> m ()-sequenceOf_ l = getSequenced . foldMapOf l (Sequenced . liftM skip)-{-# INLINE sequenceOf_ #-}---- | The sum of a collection of actions, generalizing 'concatOf'.------ @'asum' ≡ 'asumOf' 'folded'@------ @--- 'asumOf' :: 'Alternative' f => 'Getter' a c           -> a -> f c--- 'asumOf' :: 'Alternative' f => 'Fold' a c             -> a -> f c--- 'asumOf' :: 'Alternative' f => 'Simple' 'Lens' a c      -> a -> f c--- 'asumOf' :: 'Alternative' f => 'Simple' 'Control.Lens.Iso.Iso' a c       -> a -> f c--- 'asumOf' :: 'Alternative' f => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> f c--- @-asumOf :: Alternative f => Getting (Endo (f c)) a b (f c) d -> a -> f c-asumOf l = foldrOf l (<|>) Applicative.empty-{-# INLINE asumOf #-}---- | The sum of a collection of actions, generalizing 'concatOf'.------ @'msum' ≡ 'msumOf' 'folded'@------ @--- 'msumOf' :: 'MonadPlus' m => 'Getter' a c           -> a -> m c--- 'msumOf' :: 'MonadPlus' m => 'Fold' a c             -> a -> m c--- 'msumOf' :: 'MonadPlus' m => 'Simple' 'Lens' a c      -> a -> m c--- 'msumOf' :: 'MonadPlus' m => 'Simple' 'Control.Lens.Iso.Iso' a c       -> a -> m c--- 'msumOf' :: 'MonadPlus' m => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> m c--- @-msumOf :: MonadPlus m => Getting (Endo (m c)) a b (m c) d -> a -> m c-msumOf l = foldrOf l mplus mzero-{-# INLINE msumOf #-}---- | Does the element occur anywhere within a given 'Fold' of the structure?------ >>> elemOf both "hello" ("hello","world")--- True------ @'elem' ≡ 'elemOf' 'folded'@------ @--- 'elemOf' :: 'Eq' c => 'Getter' a c           -> c -> a -> 'Bool'--- 'elemOf' :: 'Eq' c => 'Fold' a c             -> c -> a -> 'Bool'--- 'elemOf' :: 'Eq' c => 'Simple' 'Lens' a c      -> c -> a -> 'Bool'--- 'elemOf' :: 'Eq' c => 'Simple' 'Control.Lens.Iso.Iso' a c       -> c -> a -> 'Bool'--- 'elemOf' :: 'Eq' c => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> c -> a -> 'Bool'--- @-elemOf :: Eq c => Getting Any a b c d -> c -> a -> Bool-elemOf l = anyOf l . (==)-{-# INLINE elemOf #-}---- | Does the element not occur anywhere within a given 'Fold' of the structure?------ @'notElem' ≡ 'notElemOf' 'folded'@------ @--- 'notElemOf' :: 'Eq' c => 'Getter' a c           -> c -> a -> 'Bool'--- 'notElemOf' :: 'Eq' c => 'Fold' a c             -> c -> a -> 'Bool'--- 'notElemOf' :: 'Eq' c => 'Simple' 'Control.Lens.Iso.Iso' a c       -> c -> a -> 'Bool'--- 'notElemOf' :: 'Eq' c => 'Simple' 'Lens' a c      -> c -> a -> 'Bool'--- 'notElemOf' :: 'Eq' c => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> c -> a -> 'Bool'--- @-notElemOf :: Eq c => Getting All a b c d -> c -> a -> Bool-notElemOf l = allOf l . (/=)-{-# INLINE notElemOf #-}---- | Map a function over all the targets of a 'Fold' of a container and concatenate the resulting lists.------ @'concatMap' ≡ 'concatMapOf' 'folded'@------ @--- 'concatMapOf' :: 'Getter' a c           -> (c -> [e]) -> a -> [e]--- 'concatMapOf' :: 'Fold' a c             -> (c -> [e]) -> a -> [e]--- 'concatMapOf' :: 'Simple' 'Lens' a c      -> (c -> [e]) -> a -> [e]--- 'concatMapOf' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> [e]) -> a -> [e]--- 'concatMapOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> [e]) -> a -> [e]--- @-concatMapOf :: Getting [e] a b c d -> (c -> [e]) -> a -> [e]-concatMapOf l ces = runAccessor . l (Accessor . ces)-{-# INLINE concatMapOf #-}---- | Concatenate all of the lists targeted by a 'Fold' into a longer list.------ >>> concatOf both ("pan","ama")--- "panama"------ @--- 'concat' ≡ 'concatOf' 'folded'--- 'concatOf' ≡ 'view'--- @------ @--- 'concatOf' :: 'Getter' a [e]           -> a -> [e]--- 'concatOf' :: 'Fold' a [e]             -> a -> [e]--- 'concatOf' :: 'Simple' 'Control.Lens.Iso.Iso' a [e]       -> a -> [e]--- 'concatOf' :: 'Simple' 'Lens' a [e]      -> a -> [e]--- 'concatOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a [e] -> a -> [e]--- @-concatOf :: Getting [e] a b [e] d -> a -> [e]-concatOf = view-{-# INLINE concatOf #-}---- |--- Note: this can be rather inefficient for large containers.------ @'length' ≡ 'lengthOf' 'folded'@------ >>> lengthOf _1 ("hello",())--- 1------ @'lengthOf' ('folded' . 'folded') :: 'Foldable' f => f (g a) -> 'Int'@------ @--- 'lengthOf' :: 'Getter' a c           -> a -> 'Int'--- 'lengthOf' :: 'Fold' a c             -> a -> 'Int'--- 'lengthOf' :: 'Simple' 'Lens' a c      -> a -> 'Int'--- 'lengthOf' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> a -> 'Int'--- 'lengthOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> 'Int'--- @-lengthOf :: Getting (Sum Int) a b c d -> a -> Int-lengthOf l = getSum . foldMapOf l (\_ -> Sum 1)-{-# INLINE lengthOf #-}---- | Perform a safe 'head' of a 'Fold' or 'Control.Lens.Traversal.Traversal' or retrieve 'Just' the result--- from a 'Getter' or 'Lens'. See also ('^?').------ @'Data.Maybe.listToMaybe' '.' 'toList' ≡ 'headOf' 'folded'@------ @--- 'headOf' :: 'Getter' a c           -> a -> 'Maybe' c--- 'headOf' :: 'Fold' a c             -> a -> 'Maybe' c--- 'headOf' :: 'Simple' 'Lens' a c      -> a -> 'Maybe' c--- 'headOf' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> a -> 'Maybe' c--- 'headOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> 'Maybe' c--- @-headOf :: Getting (First c) a b c d -> a -> Maybe c-headOf l = getFirst . foldMapOf l (First . Just)-{-# INLINE headOf #-}---- | Perform a safe 'head' of a 'Fold' or 'Control.Lens.Traversal.Traversal' or retrieve 'Just' the result--- from a 'Getter' or 'Lens'.------ When using a 'Control.Lens.Traversal.Traversal' as a partial 'Control.Lens.Type.Lens', or a 'Fold' as a partial 'Getter' this can be a convenient--- way to extract the optional value.------ @('^?') ≡ 'flip' 'headOf'@------ @--- ('^?') :: a -> 'Getter' a c           -> 'Maybe' c--- ('^?') :: a -> 'Fold' a c             -> 'Maybe' c--- ('^?') :: a -> 'Simple' 'Lens' a c      -> 'Maybe' c--- ('^?') :: a -> 'Simple' 'Control.Lens.Iso.Iso' a c       -> 'Maybe' c--- ('^?') :: a -> 'Simple' 'Control.Lens.Traversal.Traversal' a c -> 'Maybe' c--- @-(^?) :: a -> Getting (First c) a b c d -> Maybe c-a ^? l = getFirst (foldMapOf l (First . Just) a)-{-# INLINE (^?) #-}---- | Perform a safe 'last' of a 'Fold' or 'Control.Lens.Traversal.Traversal' or retrieve 'Just' the result--- from a 'Getter' or 'Lens'.------ @--- 'lastOf' :: 'Getter' a c           -> a -> 'Maybe' c--- 'lastOf' :: 'Fold' a c             -> a -> 'Maybe' c--- 'lastOf' :: 'Simple' 'Lens' a c      -> a -> 'Maybe' c--- 'lastOf' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> a -> 'Maybe' c--- 'lastOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> 'Maybe' c--- @-lastOf :: Getting (Last c) a b c d -> a -> Maybe c-lastOf l = getLast . foldMapOf l (Last . Just)-{-# INLINE lastOf #-}---- |--- Returns 'True' if this 'Fold' or 'Control.Lens.Traversal.Traversal' has no targets in the given container.------ Note: 'nullOf' on a valid 'Control.Lens.Iso.Iso', 'Lens' or 'Getter' should always return 'False'------ @'null' ≡ 'nullOf' 'folded'@------ This may be rather inefficient compared to the 'null' check of many containers.------ >>> nullOf _1 (1,2)--- False------ @'nullOf' ('folded' '.' '_1' '.' 'folded') :: 'Foldable' f => f (g a, b) -> 'Bool'@------ @--- 'nullOf' :: 'Getter' a c           -> a -> 'Bool'--- 'nullOf' :: 'Fold' a c             -> a -> 'Bool'--- 'nullOf' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> a -> 'Bool'--- 'nullOf' :: 'Simple' 'Lens' a c      -> a -> 'Bool'--- 'nullOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> 'Bool'--- @-nullOf :: Getting All a b c d -> a -> Bool-nullOf l = getAll . foldMapOf l (\_ -> All False)-{-# INLINE nullOf #-}---- |--- Obtain the maximum element (if any) targeted by a 'Fold' or 'Control.Lens.Traversal.Traversal'------ Note: maximumOf on a valid 'Control.Lens.Iso.Iso', 'Lens' or 'Getter' will always return 'Just' a value.------ @'maximum' ≡ 'fromMaybe' ('error' "empty") '.' 'maximumOf' 'folded'@------ @--- 'maximumOf' ::          'Getter' a c           -> a -> 'Maybe' c--- 'maximumOf' :: 'Ord' c => 'Fold' a c             -> a -> 'Maybe' c--- 'maximumOf' ::          'Simple' 'Control.Lens.Iso.Iso' a c       -> a -> 'Maybe' c--- 'maximumOf' ::          'Simple' 'Lens' a c      -> a -> 'Maybe' c--- 'maximumOf' :: 'Ord' c => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> 'Maybe' c--- @-maximumOf :: Getting (Max c) a b c d -> a -> Maybe c-maximumOf l = getMax . foldMapOf l Max-{-# INLINE maximumOf #-}---- |--- Obtain the minimum element (if any) targeted by a 'Fold' or 'Control.Lens.Traversal.Traversal'------ Note: minimumOf on a valid 'Control.Lens.Iso.Iso', 'Lens' or 'Getter' will always return 'Just' a value.------ @'minimum' ≡ 'Data.Maybe.fromMaybe' ('error' "empty") '.' 'minimumOf' 'folded'@------ @--- 'minimumOf' ::          'Getter' a c           -> a -> 'Maybe' c--- 'minimumOf' :: 'Ord' c => 'Fold' a c             -> a -> 'Maybe' c--- 'minimumOf' ::          'Simple' 'Control.Lens.Iso.Iso' a c       -> a -> 'Maybe' c--- 'minimumOf' ::          'Simple' 'Lens' a c      -> a -> 'Maybe' c--- 'minimumOf' :: 'Ord' c => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> 'Maybe' c--- @-minimumOf :: Getting (Min c) a b c d -> a -> Maybe c-minimumOf l = getMin . foldMapOf l Min-{-# INLINE minimumOf #-}---- |--- Obtain the maximum element (if any) targeted by a 'Fold', 'Control.Lens.Traversal.Traversal', 'Lens', 'Control.Lens.Iso.Iso',--- or 'Getter' according to a user supplied ordering.------ @'Data.Foldable.maximumBy' cmp ≡ 'Data.Maybe.fromMaybe' ('error' "empty") '.' 'maximumByOf' 'folded' cmp@------ @--- 'maximumByOf' :: 'Getter' a c           -> (c -> c -> 'Ordering') -> a -> 'Maybe' c--- 'maximumByOf' :: 'Fold' a c             -> (c -> c -> 'Ordering') -> a -> 'Maybe' c--- 'maximumByOf' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> c -> 'Ordering') -> a -> 'Maybe' c--- 'maximumByOf' :: 'Simple' 'Lens' a c      -> (c -> c -> 'Ordering') -> a -> 'Maybe' c--- 'maximumByOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> c -> 'Ordering') -> a -> 'Maybe' c--- @-maximumByOf :: Getting (Endo (Maybe c)) a b c d -> (c -> c -> Ordering) -> a -> Maybe c-maximumByOf l cmp = foldrOf l step Nothing where-  step a Nothing  = Just a-  step a (Just b) = Just (if cmp a b == GT then a else b)-{-# INLINE maximumByOf #-}---- |--- Obtain the minimum element (if any) targeted by a 'Fold', 'Control.Lens.Traversal.Traversal', 'Lens', 'Control.Lens.Iso.Iso'--- or 'Getter' according to a user supplied ordering.------ @'minimumBy' cmp ≡ 'Data.Maybe.fromMaybe' ('error' "empty") '.' 'minimumByOf' 'folded' cmp@------ @--- 'minimumByOf' :: 'Getter' a c           -> (c -> c -> 'Ordering') -> a -> 'Maybe' c--- 'minimumByOf' :: 'Fold' a c             -> (c -> c -> 'Ordering') -> a -> 'Maybe' c--- 'minimumByOf' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> c -> 'Ordering') -> a -> 'Maybe' c--- 'minimumByOf' :: 'Simple' 'Lens' a c      -> (c -> c -> 'Ordering') -> a -> 'Maybe' c--- 'minimumByOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> c -> 'Ordering') -> a -> 'Maybe' c--- @-minimumByOf :: Getting (Endo (Maybe c)) a b c d -> (c -> c -> Ordering) -> a -> Maybe c-minimumByOf l cmp = foldrOf l step Nothing where-  step a Nothing  = Just a-  step a (Just b) = Just (if cmp a b == GT then b else a)-{-# INLINE minimumByOf #-}---- | The 'findOf' function takes a 'Lens' (or 'Control.Lens.Getter.Getter', 'Control.Lens.Iso.Iso', 'Control.Lens.Fold.Fold', or 'Control.Lens.Traversal.Traversal'),--- a predicate and a structure and returns the leftmost element of the structure--- matching the predicate, or 'Nothing' if there is no such element.------ @--- 'findOf' :: 'Getter' a c           -> (c -> 'Bool') -> a -> 'Maybe' c--- 'findOf' :: 'Fold' a c             -> (c -> 'Bool') -> a -> 'Maybe' c--- 'findOf' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> 'Bool') -> a -> 'Maybe' c--- 'findOf' :: 'Simple' 'Lens' a c      -> (c -> 'Bool') -> a -> 'Maybe' c--- 'findOf' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> 'Bool') -> a -> 'Maybe' c--- @-findOf :: Getting (First c) a b c d -> (c -> Bool) -> a -> Maybe c-findOf l p = getFirst . foldMapOf l step where-  step c-    | p c       = First (Just c)-    | otherwise = First Nothing-{-# INLINE findOf #-}---- |--- A variant of 'foldrOf' that has no base case and thus may only be applied--- to lenses and structures such that the lens views at least one element of--- the structure.------ @--- 'foldr1Of' l f ≡ 'Prelude.foldr1' f '.' 'toListOf' l--- 'Data.Foldable.foldr1' ≡ 'foldr1Of' 'folded'--- @------ @--- 'foldr1Of' :: 'Getter' a c           -> (c -> c -> c) -> a -> c--- 'foldr1Of' :: 'Fold' a c             -> (c -> c -> c) -> a -> c--- 'foldr1Of' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> c -> c) -> a -> c--- 'foldr1Of' :: 'Simple' 'Lens' a c      -> (c -> c -> c) -> a -> c--- 'foldr1Of' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> c -> c) -> a -> c--- @-foldr1Of :: Getting (Endo (Maybe c)) a b c d -> (c -> c -> c) -> a -> c-foldr1Of l f xs = fromMaybe (error "foldr1Of: empty structure")-                            (foldrOf l mf Nothing xs) where-  mf x Nothing = Just x-  mf x (Just y) = Just (f x y)-{-# INLINE foldr1Of #-}---- | A variant of 'foldlOf' that has no base case and thus may only be applied to lenses and strutures such--- that the lens views at least one element of the structure.------ @--- 'foldl1Of' l f ≡ 'Prelude.foldl1Of' l f . 'toList'--- 'Data.Foldable.foldl1' ≡ 'foldl1Of' 'folded'--- @------ @--- 'foldl1Of' :: 'Getter' a c           -> (c -> c -> c) -> a -> c--- 'foldl1Of' :: 'Fold' a c             -> (c -> c -> c) -> a -> c--- 'foldl1Of' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> c -> c) -> a -> c--- 'foldl1Of' :: 'Simple' 'Lens' a c      -> (c -> c -> c) -> a -> c--- 'foldl1Of' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> c -> c) -> a -> c--- @-foldl1Of :: Getting (Dual (Endo (Maybe c))) a b c d -> (c -> c -> c) -> a -> c-foldl1Of l f xs = fromMaybe (error "foldl1Of: empty structure") (foldlOf l mf Nothing xs) where-  mf Nothing y = Just y-  mf (Just x) y = Just (f x y)-{-# INLINE foldl1Of #-}---- | Strictly fold right over the elements of a structure.------ @'Data.Foldable.foldr'' ≡ 'foldrOf'' 'folded'@------ @--- 'foldrOf'' :: 'Getter' a c           -> (c -> e -> e) -> e -> a -> e--- 'foldrOf'' :: 'Fold' a c             -> (c -> e -> e) -> e -> a -> e--- 'foldrOf'' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> e -> e) -> e -> a -> e--- 'foldrOf'' :: 'Simple' 'Lens' a c      -> (c -> e -> e) -> e -> a -> e--- 'foldrOf'' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> e -> e) -> e -> a -> e--- @-foldrOf' :: Getting (Dual (Endo (e -> e))) a b c d -> (c -> e -> e) -> e -> a -> e-foldrOf' l f z0 xs = foldlOf l f' id xs z0-  where f' k x z = k $! f x z-{-# INLINE foldrOf' #-}---- | Fold over the elements of a structure, associating to the left, but strictly.------ @'Data.Foldable.foldl'' ≡ 'foldlOf'' 'folded'@------ @--- 'foldlOf'' :: 'Getter' a c           -> (e -> c -> e) -> e -> a -> e--- 'foldlOf'' :: 'Fold' a c             -> (e -> c -> e) -> e -> a -> e--- 'foldlOf'' :: 'Simple' 'Control.Lens.Iso.Iso' a c       -> (e -> c -> e) -> e -> a -> e--- 'foldlOf'' :: 'Simple' 'Lens' a c      -> (e -> c -> e) -> e -> a -> e--- 'foldlOf'' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (e -> c -> e) -> e -> a -> e--- @-foldlOf' :: Getting (Endo (e -> e)) a b c d -> (e -> c -> e) -> e -> a -> e-foldlOf' l f z0 xs = foldrOf l f' id xs z0-  where f' x k z = k $! f z x-{-# INLINE foldlOf' #-}---- | Monadic fold over the elements of a structure, associating to the right,--- i.e. from right to left.------ @'Data.Foldable.foldrM' ≡ 'foldrMOf' 'folded'@------ @--- 'foldrMOf' :: 'Monad' m => 'Getter' a c           -> (c -> e -> m e) -> e -> a -> m e--- 'foldrMOf' :: 'Monad' m => 'Fold' a c             -> (c -> e -> m e) -> e -> a -> m e--- 'foldrMOf' :: 'Monad' m => 'Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> e -> m e) -> e -> a -> m e--- 'foldrMOf' :: 'Monad' m => 'Simple' 'Lens' a c      -> (c -> e -> m e) -> e -> a -> m e--- 'foldrMOf' :: 'Monad' m => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> e -> m e) -> e -> a -> m e--- @-foldrMOf :: Monad m-         => Getting (Dual (Endo (e -> m e))) a b c d-         -> (c -> e -> m e) -> e -> a -> m e-foldrMOf l f z0 xs = foldlOf l f' return xs z0-  where f' k x z = f x z >>= k-{-# INLINE foldrMOf #-}---- | Monadic fold over the elements of a structure, associating to the left,--- i.e. from left to right.------ @'Data.Foldable.foldlM' ≡ 'foldlMOf' 'folded'@------ @--- 'foldlMOf' :: 'Monad' m => 'Getter' a c           -> (e -> c -> m e) -> e -> a -> m e--- 'foldlMOf' :: 'Monad' m => 'Fold' a c             -> (e -> c -> m e) -> e -> a -> m e--- 'foldlMOf' :: 'Monad' m => 'Simple' 'Control.Lens.Iso.Iso' a c       -> (e -> c -> m e) -> e -> a -> m e--- 'foldlMOf' :: 'Monad' m => 'Simple' 'Lens' a c      -> (e -> c -> m e) -> e -> a -> m e--- 'foldlMOf' :: 'Monad' m => 'Simple' 'Control.Lens.Traversal.Traversal' a c -> (e -> c -> m e) -> e -> a -> m e--- @-foldlMOf :: Monad m-         => Getting (Endo (e -> m e)) a b c d-         -> (e -> c -> m e) -> e -> a -> m e-foldlMOf l f z0 xs = foldrOf l f' return xs z0-  where f' x k z = f z x >>= k-{-# INLINE foldlMOf #-}---- | Useful for storing folds in containers.-newtype ReifiedFold a c = ReifyFold { reflectFold :: Fold a c }+{-# LANGUAGE CPP #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE Trustworthy #-}++#include "lens-common.h"+{-# OPTIONS_GHC -Wno-orphans #-}+----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Fold+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  Rank2Types+--+-- A @'Fold' s a@ is a generalization of something 'Foldable'. It allows+-- you to extract multiple results from a container. A 'Foldable' container+-- can be characterized by the behavior of+-- @'Data.Foldable.foldMap' :: ('Foldable' t, 'Monoid' m) => (a -> m) -> t a -> m@.+-- Since we want to be able to work with monomorphic containers, we could+-- generalize this signature to @forall m. 'Monoid' m => (a -> m) -> s -> m@,+-- and then decorate it with 'Const' to obtain+--+-- @type 'Fold' s a = forall m. 'Monoid' m => 'Getting' m s a@+--+-- Every 'Getter' is a valid 'Fold' that simply doesn't use the 'Monoid'+-- it is passed.+--+-- In practice the type we use is slightly more complicated to allow for+-- better error messages and for it to be transformed by certain+-- 'Applicative' transformers.+--+-- Everything you can do with a 'Foldable' container, you can with with a 'Fold' and there are+-- combinators that generalize the usual 'Foldable' operations here.+----------------------------------------------------------------------------+module Control.Lens.Fold+  (+  -- * Folds+    Fold+  , IndexedFold++  -- * Getting Started+  , (^..)+  , (^?)+  , (^?!)+  , pre, ipre+  , preview, previews, ipreview, ipreviews+  , preuse, preuses, ipreuse, ipreuses++  , has, hasn't++  -- ** Building Folds+  , folding, ifolding+  , foldring, ifoldring+  , folded+  , folded64+  , unfolded+  , iterated+  , filtered+  , filteredBy+  , backwards+  , repeated+  , replicated+  , cycled+  , takingWhile+  , droppingWhile+  , worded, lined++  -- ** Folding+  , foldMapOf, foldOf+  , foldrOf, foldlOf+  , toListOf, toNonEmptyOf+  , altOf+  , anyOf, allOf, noneOf+  , andOf, orOf+  , productOf, sumOf+  , traverseOf_, forOf_, sequenceAOf_+  , traverse1Of_, for1Of_, sequence1Of_+  , mapMOf_, forMOf_, sequenceOf_+  , asumOf, msumOf+  , concatMapOf, concatOf+  , elemOf, notElemOf+  , lengthOf+  , nullOf, notNullOf+  , firstOf, first1Of, lastOf, last1Of+  , maximumOf, maximum1Of, minimumOf, minimum1Of+  , maximumByOf, minimumByOf+  , findOf+  , findMOf+  , foldrOf', foldlOf'+  , foldr1Of, foldl1Of+  , foldr1Of', foldl1Of'+  , foldrMOf, foldlMOf+  , lookupOf++  -- * Indexed Folds+  , (^@..)+  , (^@?)+  , (^@?!)++  -- ** Indexed Folding+  , ifoldMapOf+  , ifoldrOf+  , ifoldlOf+  , ianyOf+  , iallOf+  , inoneOf+  , itraverseOf_+  , iforOf_+  , imapMOf_+  , iforMOf_+  , iconcatMapOf+  , ifindOf+  , ifindMOf+  , ifoldrOf'+  , ifoldlOf'+  , ifoldrMOf+  , ifoldlMOf+  , itoListOf+  , elemIndexOf+  , elemIndicesOf+  , findIndexOf+  , findIndicesOf++  -- ** Building Indexed Folds+  , ifiltered+  , itakingWhile+  , idroppingWhile++  -- * Internal types+  , Leftmost+  , Rightmost+  , Traversed+  , Sequenced++  -- * Fold with Reified Monoid+  , foldBy+  , foldByOf+  , foldMapBy+  , foldMapByOf+  ) where++import Prelude ()++import Control.Applicative.Backwards+import Control.Comonad+import Control.Lens.Getter+import Control.Lens.Internal.Fold+import Control.Lens.Internal.Getter+import Control.Lens.Internal.Indexed+import Control.Lens.Internal.Magma+import Control.Lens.Internal.Prelude+import Control.Lens.Type+import Control.Monad as Monad+import Control.Monad.Reader+import Control.Monad.State+import Data.CallStack+import Data.Functor.Apply hiding ((<.))+import Data.Int (Int64)+import Data.List (intercalate)+import Data.Maybe (fromMaybe)+import Data.Monoid (First (..), All (..), Alt (..), Any (..))+import Data.Reflection++import qualified Data.Semigroup as Semi++-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import Control.Lens.Extras (is)+-- >>> import Data.Function+-- >>> import Data.List.Lens+-- >>> import Data.List.NonEmpty (NonEmpty (..))+-- >>> import Debug.SimpleReflect.Expr+-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g)+-- >>> import Control.DeepSeq (NFData (..), force)+-- >>> import Control.Exception (evaluate)+-- >>> import Data.Maybe (fromMaybe)+-- >>> import Data.Monoid (Sum (..))+-- >>> import System.Timeout (timeout)+-- >>> import qualified Data.Map as Map+-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f+-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g+-- >>> let timingOut :: NFData a => a -> IO a; timingOut = fmap (fromMaybe (error "timeout")) . timeout (5*10^6) . evaluate . force++infixl 8 ^.., ^?, ^?!, ^@.., ^@?, ^@?!++--------------------------+-- Folds+--------------------------++-- | Obtain a 'Fold' by lifting an operation that returns a 'Foldable' result.+--+-- This can be useful to lift operations from @Data.List@ and elsewhere into a 'Fold'.+--+-- >>> [1,2,3,4]^..folding reverse+-- [4,3,2,1]+folding :: Foldable f => (s -> f a) -> Fold s a+folding sfa agb = phantom . traverse_ agb . sfa+{-# INLINE folding #-}++ifolding :: (Foldable f, Indexable i p, Contravariant g, Applicative g) => (s -> f (i, a)) -> Over p g s t a b+ifolding sfa f = phantom . traverse_ (phantom . uncurry (indexed f)) . sfa+{-# INLINE ifolding #-}++-- | Obtain a 'Fold' by lifting 'foldr' like function.+--+-- >>> [1,2,3,4]^..foldring foldr+-- [1,2,3,4]+foldring :: (Contravariant f, Applicative f) => ((a -> f a -> f a) -> f a -> s -> f a) -> LensLike f s t a b+foldring fr f = phantom . fr (\a fa -> f a *> fa) noEffect+{-# INLINE foldring #-}++-- | Obtain 'FoldWithIndex' by lifting 'ifoldr' like function.+ifoldring :: (Indexable i p, Contravariant f, Applicative f) => ((i -> a -> f a -> f a) -> f a -> s -> f a) -> Over p f s t a b+ifoldring ifr f = phantom . ifr (\i a fa -> indexed f i a *> fa) noEffect+{-# INLINE ifoldring #-}++-- | Obtain a 'Fold' from any 'Foldable' indexed by ordinal position.+--+-- >>> Just 3^..folded+-- [3]+--+-- >>> Nothing^..folded+-- []+--+-- >>> [(1,2),(3,4)]^..folded.both+-- [1,2,3,4]+folded :: Foldable f => IndexedFold Int (f a) a+folded = conjoined (foldring foldr) (ifoldring ifoldr)+{-# INLINE folded #-}++ifoldr :: Foldable f => (Int -> a -> b -> b) -> b -> f a -> b+ifoldr f z xs = foldr (\ x g i -> i `seq` f i x (g (i+1))) (const z) xs 0+{-# INLINE ifoldr #-}++-- | Obtain a 'Fold' from any 'Foldable' indexed by ordinal position.+folded64 :: Foldable f => IndexedFold Int64 (f a) a+folded64 = conjoined (foldring foldr) (ifoldring ifoldr64)+{-# INLINE folded64 #-}++ifoldr64 :: Foldable f => (Int64 -> a -> b -> b) -> b -> f a -> b+ifoldr64 f z xs = foldr (\ x g i -> i `seq` f i x (g (i+1))) (const z) xs 0+{-# INLINE ifoldr64 #-}++-- | Form a 'Fold1' by repeating the input forever.+--+-- @+-- 'repeat' ≡ 'toListOf' 'repeated'+-- @+--+-- >>> timingOut $ 5^..taking 20 repeated+-- [5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5]+--+-- @+-- 'repeated' :: 'Fold1' a a+-- @+repeated :: Apply f => LensLike' f a a+repeated f a = as where as = f a .> as+{-# INLINE repeated #-}++-- | A 'Fold' that replicates its input @n@ times.+--+-- @+-- 'replicate' n ≡ 'toListOf' ('replicated' n)+-- @+--+-- >>> 5^..replicated 20+-- [5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5]+replicated :: Int -> Fold a a+replicated n0 f a = go n0 where+  m = f a+  go 0 = noEffect+  go n = m *> go (n - 1)+{-# INLINE replicated #-}++-- | Transform a non-empty 'Fold' into a 'Fold1' that loops over its elements over and over.+--+-- >>> timingOut $ [1,2,3]^..taking 7 (cycled traverse)+-- [1,2,3,1,2,3,1]+--+-- @+-- 'cycled' :: 'Fold1' s a -> 'Fold1' s a+-- @+cycled :: Apply f => LensLike f s t a b -> LensLike f s t a b+cycled l f a = as where as = l f a .> as+{-# INLINE cycled #-}++-- | Build a 'Fold' that unfolds its values from a seed.+--+-- @+-- 'Prelude.unfoldr' ≡ 'toListOf' '.' 'unfolded'+-- @+--+-- >>> 10^..unfolded (\b -> if b == 0 then Nothing else Just (b, b-1))+-- [10,9,8,7,6,5,4,3,2,1]+unfolded :: (b -> Maybe (a, b)) -> Fold b a+unfolded f g = go where+  go b = case f b of+    Just (a, b') -> g a *> go b'+    Nothing      -> noEffect+{-# INLINE unfolded #-}++-- | @x '^.' 'iterated' f@ returns an infinite 'Fold1' of repeated applications of @f@ to @x@.+--+-- @+-- 'toListOf' ('iterated' f) a ≡ 'iterate' f a+-- @+--+-- @+-- 'iterated' :: (a -> a) -> 'Fold1' a a+-- @+iterated :: Apply f => (a -> a) -> LensLike' f a a+iterated f g = go where+  go a = g a .> go (f a)+{-# INLINE iterated #-}++-- | Obtain a 'Fold' that can be composed with to filter another 'Lens', 'Iso', 'Getter', 'Fold' (or 'Traversal').+--+-- Note: This is /not/ a legal 'Traversal', unless you are very careful not to invalidate the predicate on the target.+--+-- Note: This is also /not/ a legal 'Prism', unless you are very careful not to inject a value that fails the predicate.+--+-- As a counter example, consider that given @evens = 'filtered' 'even'@ the second 'Traversal' law is violated:+--+-- @+-- 'Control.Lens.Setter.over' evens 'succ' '.' 'Control.Lens.Setter.over' evens 'succ' '/=' 'Control.Lens.Setter.over' evens ('succ' '.' 'succ')+-- @+--+-- So, in order for this to qualify as a legal 'Traversal' you can only use it for actions that preserve the result of the predicate!+--+-- >>> [1..10]^..folded.filtered even+-- [2,4,6,8,10]+--+-- This will preserve an index if it is present.+filtered :: (Choice p, Applicative f) => (a -> Bool) -> Optic' p f a a+filtered p = dimap (\x -> if p x then Right x else Left x) (either pure id) . right'+{-# INLINE filtered #-}++-- | Obtain a potentially empty 'IndexedTraversal' by taking the first element from another,+-- potentially empty `Fold` and using it as an index.+--+-- The resulting optic can be composed with to filter another 'Lens', 'Iso', 'Getter', 'Fold' (or 'Traversal').+--+-- >>> [(Just 2, 3), (Nothing, 4)] & mapped . filteredBy (_1 . _Just) <. _2 %@~ (*) :: [(Maybe Int, Int)]+-- [(Just 2,6),(Nothing,4)]+--+-- @+-- 'filteredBy' :: 'Fold' a i -> 'IndexedTraversal'' i a a+-- @+--+-- Note: As with 'filtered', this is /not/ a legal 'IndexedTraversal', unless you are very careful not to invalidate the predicate on the target!+filteredBy :: (Indexable i p, Applicative f) => Getting (First i) a i -> p a (f a) -> a -> f a+filteredBy p f val = case val ^? p of+  Nothing -> pure val+  Just witness -> indexed f witness val++-- | Obtain a 'Fold' by taking elements from another 'Fold', 'Lens', 'Iso', 'Getter' or 'Traversal' while a predicate holds.+--+-- @+-- 'takeWhile' p ≡ 'toListOf' ('takingWhile' p 'folded')+-- @+--+-- >>> timingOut $ toListOf (takingWhile (<=3) folded) [1..]+-- [1,2,3]+--+-- @+-- 'takingWhile' :: (a -> 'Bool') -> 'Fold' s a                         -> 'Fold' s a+-- 'takingWhile' :: (a -> 'Bool') -> 'Getter' s a                       -> 'Fold' s a+-- 'takingWhile' :: (a -> 'Bool') -> 'Traversal'' s a                   -> 'Fold' s a -- * See note below+-- 'takingWhile' :: (a -> 'Bool') -> 'Lens'' s a                        -> 'Fold' s a -- * See note below+-- 'takingWhile' :: (a -> 'Bool') -> 'Prism'' s a                       -> 'Fold' s a -- * See note below+-- 'takingWhile' :: (a -> 'Bool') -> 'Iso'' s a                         -> 'Fold' s a -- * See note below+-- 'takingWhile' :: (a -> 'Bool') -> 'IndexedTraversal'' i s a          -> 'IndexedFold' i s a -- * See note below+-- 'takingWhile' :: (a -> 'Bool') -> 'IndexedLens'' i s a               -> 'IndexedFold' i s a -- * See note below+-- 'takingWhile' :: (a -> 'Bool') -> 'IndexedFold' i s a                -> 'IndexedFold' i s a+-- 'takingWhile' :: (a -> 'Bool') -> 'IndexedGetter' i s a              -> 'IndexedFold' i s a+-- @+--+-- /Note:/ When applied to a 'Traversal', 'takingWhile' yields something that can be used as if it were a 'Traversal', but+-- which is not a 'Traversal' per the laws, unless you are careful to ensure that you do not invalidate the predicate when+-- writing back through it.+takingWhile :: (Conjoined p, Applicative f) => (a -> Bool) -> Over p (TakingWhile p f a a) s t a a -> Over p f s t a a+takingWhile p l pafb = fmap runMagma . traverse (cosieve pafb) . runTakingWhile . l flag where+  flag = cotabulate $ \wa -> let a = extract wa; r = p a in TakingWhile r a $ \pr ->+    if pr && r then Magma () wa else MagmaPure a+{-# INLINE takingWhile #-}++-- | Obtain a 'Fold' by dropping elements from another 'Fold', 'Lens', 'Iso', 'Getter' or 'Traversal' while a predicate holds.+--+-- @+-- 'dropWhile' p ≡ 'toListOf' ('droppingWhile' p 'folded')+-- @+--+-- >>> toListOf (droppingWhile (<=3) folded) [1..6]+-- [4,5,6]+--+-- >>> toListOf (droppingWhile (<=3) folded) [1,6,1]+-- [6,1]+--+-- @+-- 'droppingWhile' :: (a -> 'Bool') -> 'Fold' s a                         -> 'Fold' s a+-- 'droppingWhile' :: (a -> 'Bool') -> 'Getter' s a                       -> 'Fold' s a+-- 'droppingWhile' :: (a -> 'Bool') -> 'Traversal'' s a                   -> 'Fold' s a                -- see notes+-- 'droppingWhile' :: (a -> 'Bool') -> 'Lens'' s a                        -> 'Fold' s a                -- see notes+-- 'droppingWhile' :: (a -> 'Bool') -> 'Prism'' s a                       -> 'Fold' s a                -- see notes+-- 'droppingWhile' :: (a -> 'Bool') -> 'Iso'' s a                         -> 'Fold' s a                -- see notes+-- @+--+-- @+-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexPreservingTraversal'' s a    -> 'IndexPreservingFold' s a -- see notes+-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexPreservingLens'' s a         -> 'IndexPreservingFold' s a -- see notes+-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexPreservingGetter' s a        -> 'IndexPreservingFold' s a+-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexPreservingFold' s a          -> 'IndexPreservingFold' s a+-- @+--+-- @+-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexedTraversal'' i s a          -> 'IndexedFold' i s a       -- see notes+-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexedLens'' i s a               -> 'IndexedFold' i s a       -- see notes+-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexedGetter' i s a              -> 'IndexedFold' i s a+-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexedFold' i s a                -> 'IndexedFold' i s a+-- @+--+-- Note: Many uses of this combinator will yield something that meets the types, but not the laws of a valid+-- 'Traversal' or 'IndexedTraversal'. The 'Traversal' and 'IndexedTraversal' laws are only satisfied if the+-- new values you assign to the first target also does not pass the predicate! Otherwise subsequent traversals+-- will visit fewer elements and 'Traversal' fusion is not sound.+--+-- So for any traversal @t@ and predicate @p@, @`droppingWhile` p t@ may not be lawful, but+-- @(`Control.Lens.Traversal.dropping` 1 . `droppingWhile` p) t@ is. For example:+--+-- >>> let l  :: Traversal' [Int] Int; l  = droppingWhile (<= 1) traverse+-- >>> let l' :: Traversal' [Int] Int; l' = dropping 1 l+--+-- @l@ is not a lawful setter because @`Control.Lens.Setter.over` l f .+-- `Control.Lens.Setter.over` l g ≢ `Control.Lens.Setter.over` l (f . g)@:+--+-- >>> [1,2,3] & l .~ 0 & l .~ 4+-- [1,0,0]+-- >>> [1,2,3] & l .~ 4+-- [1,4,4]+--+-- @l'@ on the other hand behaves lawfully:+--+-- >>> [1,2,3] & l' .~ 0 & l' .~ 4+-- [1,2,4]+-- >>> [1,2,3] & l' .~ 4+-- [1,2,4]+droppingWhile :: (Conjoined p, Profunctor q, Applicative f)+              => (a -> Bool)+              -> Optical p q (Compose (State Bool) f) s t a a+              -> Optical p q f s t a a+droppingWhile p l f = (flip evalState True .# getCompose) `rmap` l g where+  g = cotabulate $ \wa -> Compose $ state $ \b -> let+      a = extract wa+      b' = b && p a+    in (if b' then pure a else cosieve f wa, b')+{-# INLINE droppingWhile #-}++-- | A 'Fold' over the individual 'words' of a 'String'.+--+-- @+-- 'worded' :: 'Fold' 'String' 'String'+-- 'worded' :: 'Traversal'' 'String' 'String'+-- @+--+-- @+-- 'worded' :: 'IndexedFold' 'Int' 'String' 'String'+-- 'worded' :: 'IndexedTraversal'' 'Int' 'String' 'String'+-- @+--+-- Note: This function type-checks as a 'Traversal' but it doesn't satisfy the laws. It's only valid to use it+-- when you don't insert any whitespace characters while traversing, and if your original 'String' contains only+-- isolated space characters (and no other characters that count as space, such as non-breaking spaces).+worded :: Applicative f => IndexedLensLike' Int f String String+worded f = fmap unwords . conjoined traverse (indexing traverse) f . words+{-# INLINE worded #-}++-- | A 'Fold' over the individual 'lines' of a 'String'.+--+-- @+-- 'lined' :: 'Fold' 'String' 'String'+-- 'lined' :: 'Traversal'' 'String' 'String'+-- @+--+-- @+-- 'lined' :: 'IndexedFold' 'Int' 'String' 'String'+-- 'lined' :: 'IndexedTraversal'' 'Int' 'String' 'String'+-- @+--+-- Note: This function type-checks as a 'Traversal' but it doesn't satisfy the laws. It's only valid to use it+-- when you don't insert any newline characters while traversing, and if your original 'String' contains only+-- isolated newline characters.+lined :: Applicative f => IndexedLensLike' Int f String String+lined f = fmap (intercalate "\n") . conjoined traverse (indexing traverse) f . lines+{-# INLINE lined #-}++--------------------------+-- Fold/Getter combinators+--------------------------++-- | Map each part of a structure viewed through a 'Lens', 'Getter',+-- 'Fold' or 'Traversal' to a monoid and combine the results.+--+-- >>> foldMapOf (folded . both . _Just) Sum [(Just 21, Just 21)]+-- Sum {getSum = 42}+--+-- @+-- 'Data.Foldable.foldMap' = 'foldMapOf' 'folded'+-- @+--+-- @+-- 'foldMapOf' ≡ 'views'+-- 'ifoldMapOf' l = 'foldMapOf' l '.' 'Indexed'+-- @+--+-- @+-- 'foldMapOf' ::                'Getter' s a      -> (a -> r) -> s -> r+-- 'foldMapOf' :: 'Monoid' r    => 'Fold' s a        -> (a -> r) -> s -> r+-- 'foldMapOf' :: 'Semigroup' r => 'Fold1' s a       -> (a -> r) -> s -> r+-- 'foldMapOf' ::                'Lens'' s a       -> (a -> r) -> s -> r+-- 'foldMapOf' ::                'Iso'' s a        -> (a -> r) -> s -> r+-- 'foldMapOf' :: 'Monoid' r    => 'Traversal'' s a  -> (a -> r) -> s -> r+-- 'foldMapOf' :: 'Semigroup' r => 'Traversal1'' s a -> (a -> r) -> s -> r+-- 'foldMapOf' :: 'Monoid' r    => 'Prism'' s a      -> (a -> r) -> s -> r+-- @+--+-- @+-- 'foldMapOf' :: 'Getting' r s a -> (a -> r) -> s -> r+-- @+foldMapOf :: Getting r s a -> (a -> r) -> s -> r+foldMapOf = coerce+{-# INLINE foldMapOf #-}++-- | Combine the elements of a structure viewed through a 'Lens', 'Getter',+-- 'Fold' or 'Traversal' using a monoid.+--+-- >>> foldOf (folded.folded) [[Sum 1,Sum 4],[Sum 8, Sum 8],[Sum 21]]+-- Sum {getSum = 42}+--+-- @+-- 'Data.Foldable.fold' = 'foldOf' 'folded'+-- @+--+-- @+-- 'foldOf' ≡ 'view'+-- @+--+-- @+-- 'foldOf' ::             'Getter' s m     -> s -> m+-- 'foldOf' :: 'Monoid' m => 'Fold' s m       -> s -> m+-- 'foldOf' ::             'Lens'' s m      -> s -> m+-- 'foldOf' ::             'Iso'' s m       -> s -> m+-- 'foldOf' :: 'Monoid' m => 'Traversal'' s m -> s -> m+-- 'foldOf' :: 'Monoid' m => 'Prism'' s m     -> s -> m+-- @+foldOf :: Getting a s a -> s -> a+foldOf l = getConst #. l Const+{-# INLINE foldOf #-}++-- | Right-associative fold of parts of a structure that are viewed through a 'Lens', 'Getter', 'Fold' or 'Traversal'.+--+-- @+-- 'Data.Foldable.foldr' ≡ 'foldrOf' 'folded'+-- @+--+-- @+-- 'foldrOf' :: 'Getter' s a     -> (a -> r -> r) -> r -> s -> r+-- 'foldrOf' :: 'Fold' s a       -> (a -> r -> r) -> r -> s -> r+-- 'foldrOf' :: 'Lens'' s a      -> (a -> r -> r) -> r -> s -> r+-- 'foldrOf' :: 'Iso'' s a       -> (a -> r -> r) -> r -> s -> r+-- 'foldrOf' :: 'Traversal'' s a -> (a -> r -> r) -> r -> s -> r+-- 'foldrOf' :: 'Prism'' s a     -> (a -> r -> r) -> r -> s -> r+-- @+--+-- @+-- 'ifoldrOf' l ≡ 'foldrOf' l '.' 'Indexed'+-- @+--+-- @+-- 'foldrOf' :: 'Getting' ('Endo' r) s a -> (a -> r -> r) -> r -> s -> r+-- @+foldrOf :: Getting (Endo r) s a -> (a -> r -> r) -> r -> s -> r+foldrOf l f z = flip appEndo z . foldMapOf l (Endo #. f)+{-# INLINE foldrOf #-}++-- | Left-associative fold of the parts of a structure that are viewed through a 'Lens', 'Getter', 'Fold' or 'Traversal'.+--+-- @+-- 'Data.Foldable.foldl' ≡ 'foldlOf' 'folded'+-- @+--+-- @+-- 'foldlOf' :: 'Getter' s a     -> (r -> a -> r) -> r -> s -> r+-- 'foldlOf' :: 'Fold' s a       -> (r -> a -> r) -> r -> s -> r+-- 'foldlOf' :: 'Lens'' s a      -> (r -> a -> r) -> r -> s -> r+-- 'foldlOf' :: 'Iso'' s a       -> (r -> a -> r) -> r -> s -> r+-- 'foldlOf' :: 'Traversal'' s a -> (r -> a -> r) -> r -> s -> r+-- 'foldlOf' :: 'Prism'' s a     -> (r -> a -> r) -> r -> s -> r+-- @+foldlOf :: Getting (Dual (Endo r)) s a -> (r -> a -> r) -> r -> s -> r+foldlOf l f z = (flip appEndo z .# getDual) `rmap` foldMapOf l (Dual #. Endo #. flip f)+{-# INLINE foldlOf #-}++-- | Extract a list of the targets of a 'Fold'. See also ('^..').+--+-- @+-- 'Data.Foldable.toList' ≡ 'toListOf' 'folded'+-- ('^..') ≡ 'flip' 'toListOf'+-- @++-- >>> toListOf both ("hello","world")+-- ["hello","world"]+--+-- @+-- 'toListOf' :: 'Getter' s a     -> s -> [a]+-- 'toListOf' :: 'Fold' s a       -> s -> [a]+-- 'toListOf' :: 'Lens'' s a      -> s -> [a]+-- 'toListOf' :: 'Iso'' s a       -> s -> [a]+-- 'toListOf' :: 'Traversal'' s a -> s -> [a]+-- 'toListOf' :: 'Prism'' s a     -> s -> [a]+-- @+toListOf :: Getting (Endo [a]) s a -> s -> [a]+toListOf l = foldrOf l (:) []+{-# INLINE toListOf #-}++-- | Extract a 'NonEmpty' of the targets of 'Fold1'.+--+-- >>> toNonEmptyOf both1 ("hello", "world")+-- "hello" :| ["world"]+--+-- @+-- 'toNonEmptyOf' :: 'Getter' s a      -> s -> NonEmpty a+-- 'toNonEmptyOf' :: 'Fold1' s a       -> s -> NonEmpty a+-- 'toNonEmptyOf' :: 'Lens'' s a       -> s -> NonEmpty a+-- 'toNonEmptyOf' :: 'Iso'' s a        -> s -> NonEmpty a+-- 'toNonEmptyOf' :: 'Traversal1'' s a -> s -> NonEmpty a+-- @+toNonEmptyOf :: Getting (NonEmptyDList a) s a -> s -> NonEmpty a+toNonEmptyOf l = flip getNonEmptyDList [] . foldMapOf l (NonEmptyDList #. (:|))++-- | Calls 'pure' on the target of a 'Lens', 'Getter', or 'Iso'.+--+-- Calls 'pure' on the targets of a 'Traversal', 'Fold', or 'Prism', and+-- combines them with '<|>' (or `empty` if none).  Intuitively, it collects+-- targets into an 'Alternative' until the container fills up or it runs out of+-- targets, whichever comes first.+--+-- Generalizes 'toListOf' and '(^?)'.+--+-- >>> altOf both ("hello", "world") :: [String]+-- ["hello","world"]+-- >>> altOf both ("hello", "world") :: Maybe String+-- Just "hello"+--+-- @+-- 'altOf' :: Applicative f => 'Lens'' s a      -> s -> f a+-- 'altOf' :: Applicative f => 'Getter' s a     -> s -> f a+-- 'altOf' :: Applicative f => 'Iso'' s a       -> s -> f a+--+-- 'altOf' :: Alternative f => 'Traversal'' s a -> s -> f a+-- 'altOf' :: Alternative f => 'Fold' s a       -> s -> f a+-- 'altOf' :: Alternative f => 'Prism'' s a     -> s -> f a+-- @+altOf :: Applicative f => Getting (Alt f a) s a -> s -> f a+altOf l = getAlt #. views l (Alt #. pure)+{-# INLINE altOf #-}++-- | A convenient infix (flipped) version of 'toListOf'.+--+-- >>> [[1,2],[3]]^..id+-- [[[1,2],[3]]]+-- >>> [[1,2],[3]]^..traverse+-- [[1,2],[3]]+-- >>> [[1,2],[3]]^..traverse.traverse+-- [1,2,3]+--+-- >>> (1,2)^..both+-- [1,2]+--+-- @+-- 'Data.Foldable.toList' xs ≡ xs '^..' 'folded'+-- ('^..') ≡ 'flip' 'toListOf'+-- @+--+-- @+-- ('^..') :: s -> 'Getter' s a     -> [a]+-- ('^..') :: s -> 'Fold' s a       -> [a]+-- ('^..') :: s -> 'Lens'' s a      -> [a]+-- ('^..') :: s -> 'Iso'' s a       -> [a]+-- ('^..') :: s -> 'Traversal'' s a -> [a]+-- ('^..') :: s -> 'Prism'' s a     -> [a]+-- @+(^..) :: s -> Getting (Endo [a]) s a -> [a]+s ^.. l = toListOf l s+{-# INLINE (^..) #-}++-- | Returns 'True' if every target of a 'Fold' is 'True'.+--+-- >>> andOf both (True,False)+-- False+-- >>> andOf both (True,True)+-- True+--+-- @+-- 'Data.Foldable.and' ≡ 'andOf' 'folded'+-- @+--+-- @+-- 'andOf' :: 'Getter' s 'Bool'     -> s -> 'Bool'+-- 'andOf' :: 'Fold' s 'Bool'       -> s -> 'Bool'+-- 'andOf' :: 'Lens'' s 'Bool'      -> s -> 'Bool'+-- 'andOf' :: 'Iso'' s 'Bool'       -> s -> 'Bool'+-- 'andOf' :: 'Traversal'' s 'Bool' -> s -> 'Bool'+-- 'andOf' :: 'Prism'' s 'Bool'     -> s -> 'Bool'+-- @+andOf :: Getting All s Bool -> s -> Bool+andOf l = getAll #. foldMapOf l All+{-# INLINE andOf #-}++-- | Returns 'True' if any target of a 'Fold' is 'True'.+--+-- >>> orOf both (True,False)+-- True+-- >>> orOf both (False,False)+-- False+--+-- @+-- 'Data.Foldable.or' ≡ 'orOf' 'folded'+-- @+--+-- @+-- 'orOf' :: 'Getter' s 'Bool'     -> s -> 'Bool'+-- 'orOf' :: 'Fold' s 'Bool'       -> s -> 'Bool'+-- 'orOf' :: 'Lens'' s 'Bool'      -> s -> 'Bool'+-- 'orOf' :: 'Iso'' s 'Bool'       -> s -> 'Bool'+-- 'orOf' :: 'Traversal'' s 'Bool' -> s -> 'Bool'+-- 'orOf' :: 'Prism'' s 'Bool'     -> s -> 'Bool'+-- @+orOf :: Getting Any s Bool -> s -> Bool+orOf l = getAny #. foldMapOf l Any+{-# INLINE orOf #-}++-- | Returns 'True' if any target of a 'Fold' satisfies a predicate.+--+-- >>> anyOf both (=='x') ('x','y')+-- True+-- >>> import Data.Data.Lens+-- >>> anyOf biplate (== "world") (((),2::Int),"hello",("world",11::Int))+-- True+--+-- @+-- 'Data.Foldable.any' ≡ 'anyOf' 'folded'+-- @+--+-- @+-- 'ianyOf' l ≡ 'anyOf' l '.' 'Indexed'+-- @+--+-- @+-- 'anyOf' :: 'Getter' s a     -> (a -> 'Bool') -> s -> 'Bool'+-- 'anyOf' :: 'Fold' s a       -> (a -> 'Bool') -> s -> 'Bool'+-- 'anyOf' :: 'Lens'' s a      -> (a -> 'Bool') -> s -> 'Bool'+-- 'anyOf' :: 'Iso'' s a       -> (a -> 'Bool') -> s -> 'Bool'+-- 'anyOf' :: 'Traversal'' s a -> (a -> 'Bool') -> s -> 'Bool'+-- 'anyOf' :: 'Prism'' s a     -> (a -> 'Bool') -> s -> 'Bool'+-- @+anyOf :: Getting Any s a -> (a -> Bool) -> s -> Bool+anyOf l f = getAny #. foldMapOf l (Any #. f)+{-# INLINE anyOf #-}++-- | Returns 'True' if every target of a 'Fold' satisfies a predicate.+--+-- >>> allOf both (>=3) (4,5)+-- True+-- >>> allOf folded (>=2) [1..10]+-- False+--+-- @+-- 'Data.Foldable.all' ≡ 'allOf' 'folded'+-- @+--+-- @+-- 'iallOf' l = 'allOf' l '.' 'Indexed'+-- @+--+-- @+-- 'allOf' :: 'Getter' s a     -> (a -> 'Bool') -> s -> 'Bool'+-- 'allOf' :: 'Fold' s a       -> (a -> 'Bool') -> s -> 'Bool'+-- 'allOf' :: 'Lens'' s a      -> (a -> 'Bool') -> s -> 'Bool'+-- 'allOf' :: 'Iso'' s a       -> (a -> 'Bool') -> s -> 'Bool'+-- 'allOf' :: 'Traversal'' s a -> (a -> 'Bool') -> s -> 'Bool'+-- 'allOf' :: 'Prism'' s a     -> (a -> 'Bool') -> s -> 'Bool'+-- @+allOf :: Getting All s a -> (a -> Bool) -> s -> Bool+allOf l f = getAll #. foldMapOf l (All #. f)+{-# INLINE allOf #-}++-- | Returns 'True' only if no targets of a 'Fold' satisfy a predicate.+--+-- >>> noneOf each (is _Nothing) (Just 3, Just 4, Just 5)+-- True+-- >>> noneOf (folded.folded) (<10) [[13,99,20],[3,71,42]]+-- False+--+-- @+-- 'inoneOf' l = 'noneOf' l '.' 'Indexed'+-- @+--+-- @+-- 'noneOf' :: 'Getter' s a     -> (a -> 'Bool') -> s -> 'Bool'+-- 'noneOf' :: 'Fold' s a       -> (a -> 'Bool') -> s -> 'Bool'+-- 'noneOf' :: 'Lens'' s a      -> (a -> 'Bool') -> s -> 'Bool'+-- 'noneOf' :: 'Iso'' s a       -> (a -> 'Bool') -> s -> 'Bool'+-- 'noneOf' :: 'Traversal'' s a -> (a -> 'Bool') -> s -> 'Bool'+-- 'noneOf' :: 'Prism'' s a     -> (a -> 'Bool') -> s -> 'Bool'+-- @+noneOf :: Getting Any s a -> (a -> Bool) -> s -> Bool+noneOf l f = not . anyOf l f+{-# INLINE noneOf #-}++-- | Calculate the 'Product' of every number targeted by a 'Fold'.+--+-- >>> productOf both (4,5)+-- 20+-- >>> productOf folded [1,2,3,4,5]+-- 120+--+-- @+-- 'Data.Foldable.product' ≡ 'productOf' 'folded'+-- @+--+-- This operation may be more strict than you would expect. If you+-- want a lazier version use @'ala' 'Product' '.' 'foldMapOf'@+--+-- @+-- 'productOf' :: 'Num' a => 'Getter' s a     -> s -> a+-- 'productOf' :: 'Num' a => 'Fold' s a       -> s -> a+-- 'productOf' :: 'Num' a => 'Lens'' s a      -> s -> a+-- 'productOf' :: 'Num' a => 'Iso'' s a       -> s -> a+-- 'productOf' :: 'Num' a => 'Traversal'' s a -> s -> a+-- 'productOf' :: 'Num' a => 'Prism'' s a     -> s -> a+-- @+productOf :: Num a => Getting (Endo (Endo a)) s a -> s -> a+productOf l = foldlOf' l (*) 1+{-# INLINE productOf #-}++-- | Calculate the 'Sum' of every number targeted by a 'Fold'.+--+-- >>> sumOf both (5,6)+-- 11+-- >>> sumOf folded [1,2,3,4]+-- 10+-- >>> sumOf (folded.both) [(1,2),(3,4)]+-- 10+-- >>> import Data.Data.Lens+-- >>> sumOf biplate [(1::Int,[]),(2,[(3::Int,4::Int)])] :: Int+-- 10+--+-- @+-- 'Data.Foldable.sum' ≡ 'sumOf' 'folded'+-- @+--+-- This operation may be more strict than you would expect. If you+-- want a lazier version use @'ala' 'Sum' '.' 'foldMapOf'@+--+-- @+-- 'sumOf' '_1' :: 'Num' a => (a, b) -> a+-- 'sumOf' ('folded' '.' 'Control.Lens.Tuple._1') :: ('Foldable' f, 'Num' a) => f (a, b) -> a+-- @+--+-- @+-- 'sumOf' :: 'Num' a => 'Getter' s a     -> s -> a+-- 'sumOf' :: 'Num' a => 'Fold' s a       -> s -> a+-- 'sumOf' :: 'Num' a => 'Lens'' s a      -> s -> a+-- 'sumOf' :: 'Num' a => 'Iso'' s a       -> s -> a+-- 'sumOf' :: 'Num' a => 'Traversal'' s a -> s -> a+-- 'sumOf' :: 'Num' a => 'Prism'' s a     -> s -> a+-- @+sumOf :: Num a => Getting (Endo (Endo a)) s a -> s -> a+sumOf l = foldlOf' l (+) 0+{-# INLINE sumOf #-}++-- | Traverse over all of the targets of a 'Fold' (or 'Getter'), computing an 'Applicative' (or 'Functor')-based answer,+-- but unlike 'Control.Lens.Traversal.traverseOf' do not construct a new structure. 'traverseOf_' generalizes+-- 'Data.Foldable.traverse_' to work over any 'Fold'.+--+-- When passed a 'Getter', 'traverseOf_' can work over any 'Functor', but when passed a 'Fold', 'traverseOf_' requires+-- an 'Applicative'.+--+-- >>> traverseOf_ both putStrLn ("hello","world")+-- hello+-- world+--+-- @+-- 'Data.Foldable.traverse_' ≡ 'traverseOf_' 'folded'+-- @+--+-- @+-- 'traverseOf_' '_2' :: 'Functor' f => (c -> f r) -> (d, c) -> f ()+-- 'traverseOf_' 'Control.Lens.Prism._Left' :: 'Applicative' f => (a -> f b) -> 'Either' a c -> f ()+-- @+--+-- @+-- 'itraverseOf_' l ≡ 'traverseOf_' l '.' 'Indexed'+-- @+--+-- The rather specific signature of 'traverseOf_' allows it to be used as if the signature was any of:+--+-- @+-- 'traverseOf_' :: 'Functor' f     => 'Getter' s a     -> (a -> f r) -> s -> f ()+-- 'traverseOf_' :: 'Applicative' f => 'Fold' s a       -> (a -> f r) -> s -> f ()+-- 'traverseOf_' :: 'Functor' f     => 'Lens'' s a      -> (a -> f r) -> s -> f ()+-- 'traverseOf_' :: 'Functor' f     => 'Iso'' s a       -> (a -> f r) -> s -> f ()+-- 'traverseOf_' :: 'Applicative' f => 'Traversal'' s a -> (a -> f r) -> s -> f ()+-- 'traverseOf_' :: 'Applicative' f => 'Prism'' s a     -> (a -> f r) -> s -> f ()+-- @+traverseOf_ :: Functor f => Getting (Traversed r f) s a -> (a -> f r) -> s -> f ()+traverseOf_ l f = void . getTraversed #. foldMapOf l (Traversed #. f)+{-# INLINE traverseOf_ #-}++-- | Traverse over all of the targets of a 'Fold' (or 'Getter'), computing an 'Applicative' (or 'Functor')-based answer,+-- but unlike 'Control.Lens.Traversal.forOf' do not construct a new structure. 'forOf_' generalizes+-- 'Data.Foldable.for_' to work over any 'Fold'.+--+-- When passed a 'Getter', 'forOf_' can work over any 'Functor', but when passed a 'Fold', 'forOf_' requires+-- an 'Applicative'.+--+-- @+-- 'for_' ≡ 'forOf_' 'folded'+-- @+--+-- >>> forOf_ both ("hello","world") putStrLn+-- hello+-- world+--+-- The rather specific signature of 'forOf_' allows it to be used as if the signature was any of:+--+-- @+-- 'iforOf_' l s ≡ 'forOf_' l s '.' 'Indexed'+-- @+--+-- @+-- 'forOf_' :: 'Functor' f     => 'Getter' s a     -> s -> (a -> f r) -> f ()+-- 'forOf_' :: 'Applicative' f => 'Fold' s a       -> s -> (a -> f r) -> f ()+-- 'forOf_' :: 'Functor' f     => 'Lens'' s a      -> s -> (a -> f r) -> f ()+-- 'forOf_' :: 'Functor' f     => 'Iso'' s a       -> s -> (a -> f r) -> f ()+-- 'forOf_' :: 'Applicative' f => 'Traversal'' s a -> s -> (a -> f r) -> f ()+-- 'forOf_' :: 'Applicative' f => 'Prism'' s a     -> s -> (a -> f r) -> f ()+-- @+forOf_ :: Functor f => Getting (Traversed r f) s a -> s -> (a -> f r) -> f ()+forOf_ = flip . traverseOf_+{-# INLINE forOf_ #-}++-- | Evaluate each action in observed by a 'Fold' on a structure from left to right, ignoring the results.+--+-- @+-- 'sequenceA_' ≡ 'sequenceAOf_' 'folded'+-- @+--+-- >>> sequenceAOf_ both (putStrLn "hello",putStrLn "world")+-- hello+-- world+--+-- @+-- 'sequenceAOf_' :: 'Functor' f     => 'Getter' s (f a)     -> s -> f ()+-- 'sequenceAOf_' :: 'Applicative' f => 'Fold' s (f a)       -> s -> f ()+-- 'sequenceAOf_' :: 'Functor' f     => 'Lens'' s (f a)      -> s -> f ()+-- 'sequenceAOf_' :: 'Functor' f     => 'Iso'' s (f a)       -> s -> f ()+-- 'sequenceAOf_' :: 'Applicative' f => 'Traversal'' s (f a) -> s -> f ()+-- 'sequenceAOf_' :: 'Applicative' f => 'Prism'' s (f a)     -> s -> f ()+-- @+sequenceAOf_ :: Functor f => Getting (Traversed a f) s (f a) -> s -> f ()+sequenceAOf_ l = void . getTraversed #. foldMapOf l Traversed+{-# INLINE sequenceAOf_ #-}++-- | Traverse over all of the targets of a 'Fold1', computing an 'Apply' based answer.+--+-- As long as you have 'Applicative' or 'Functor' effect you are better using 'traverseOf_'.+-- The 'traverse1Of_' is useful only when you have genuine 'Apply' effect.+--+-- >>> traverse1Of_ both1 (\ks -> Map.fromList [ (k, ()) | k <- ks ]) ("abc", "bcd")+-- fromList [('b',()),('c',())]+--+-- @+-- 'traverse1Of_' :: 'Apply' f => 'Fold1' s a -> (a -> f r) -> s -> f ()+-- @+--+-- @since 4.16+traverse1Of_ :: Functor f => Getting (TraversedF r f) s a -> (a -> f r) -> s -> f ()+traverse1Of_ l f = void . getTraversedF #. foldMapOf l (TraversedF #. f)+{-# INLINE traverse1Of_ #-}++-- | See 'forOf_' and 'traverse1Of_'.+--+-- >>> for1Of_ both1 ("abc", "bcd") (\ks -> Map.fromList [ (k, ()) | k <- ks ])+-- fromList [('b',()),('c',())]+--+-- @+-- 'for1Of_' :: 'Apply' f => 'Fold1' s a -> s -> (a -> f r) -> f ()+-- @+--+-- @since 4.16+for1Of_ :: Functor f => Getting (TraversedF r f) s a -> s -> (a -> f r) -> f ()+for1Of_ = flip . traverse1Of_+{-# INLINE for1Of_ #-}++-- | See 'sequenceAOf_' and 'traverse1Of_'.+--+-- @+-- 'sequence1Of_' :: 'Apply' f => 'Fold1' s (f a) -> s -> f ()+-- @+--+-- @since 4.16+sequence1Of_ :: Functor f => Getting (TraversedF a f) s (f a) -> s -> f ()+sequence1Of_ l = void . getTraversedF #. foldMapOf l TraversedF+{-# INLINE sequence1Of_ #-}++-- | Map each target of a 'Fold' on a structure to a monadic action, evaluate these actions from left to right, and ignore the results.+--+-- >>> mapMOf_ both putStrLn ("hello","world")+-- hello+-- world+--+-- @+-- 'Data.Foldable.mapM_' ≡ 'mapMOf_' 'folded'+-- @+--+-- @+-- 'mapMOf_' :: 'Monad' m => 'Getter' s a     -> (a -> m r) -> s -> m ()+-- 'mapMOf_' :: 'Monad' m => 'Fold' s a       -> (a -> m r) -> s -> m ()+-- 'mapMOf_' :: 'Monad' m => 'Lens'' s a      -> (a -> m r) -> s -> m ()+-- 'mapMOf_' :: 'Monad' m => 'Iso'' s a       -> (a -> m r) -> s -> m ()+-- 'mapMOf_' :: 'Monad' m => 'Traversal'' s a -> (a -> m r) -> s -> m ()+-- 'mapMOf_' :: 'Monad' m => 'Prism'' s a     -> (a -> m r) -> s -> m ()+-- @+mapMOf_ :: Monad m => Getting (Sequenced r m) s a -> (a -> m r) -> s -> m ()+mapMOf_ l f = liftM skip . getSequenced #. foldMapOf l (Sequenced #. f)+{-# INLINE mapMOf_ #-}++-- | 'forMOf_' is 'mapMOf_' with two of its arguments flipped.+--+-- >>> forMOf_ both ("hello","world") putStrLn+-- hello+-- world+--+-- @+-- 'Data.Foldable.forM_' ≡ 'forMOf_' 'folded'+-- @+--+-- @+-- 'forMOf_' :: 'Monad' m => 'Getter' s a     -> s -> (a -> m r) -> m ()+-- 'forMOf_' :: 'Monad' m => 'Fold' s a       -> s -> (a -> m r) -> m ()+-- 'forMOf_' :: 'Monad' m => 'Lens'' s a      -> s -> (a -> m r) -> m ()+-- 'forMOf_' :: 'Monad' m => 'Iso'' s a       -> s -> (a -> m r) -> m ()+-- 'forMOf_' :: 'Monad' m => 'Traversal'' s a -> s -> (a -> m r) -> m ()+-- 'forMOf_' :: 'Monad' m => 'Prism'' s a     -> s -> (a -> m r) -> m ()+-- @+forMOf_ :: Monad m => Getting (Sequenced r m) s a -> s -> (a -> m r) -> m ()+forMOf_ = flip . mapMOf_+{-# INLINE forMOf_ #-}++-- | Evaluate each monadic action referenced by a 'Fold' on the structure from left to right, and ignore the results.+--+-- >>> sequenceOf_ both (putStrLn "hello",putStrLn "world")+-- hello+-- world+--+-- @+-- 'Data.Foldable.sequence_' ≡ 'sequenceOf_' 'folded'+-- @+--+-- @+-- 'sequenceOf_' :: 'Monad' m => 'Getter' s (m a)     -> s -> m ()+-- 'sequenceOf_' :: 'Monad' m => 'Fold' s (m a)       -> s -> m ()+-- 'sequenceOf_' :: 'Monad' m => 'Lens'' s (m a)      -> s -> m ()+-- 'sequenceOf_' :: 'Monad' m => 'Iso'' s (m a)       -> s -> m ()+-- 'sequenceOf_' :: 'Monad' m => 'Traversal'' s (m a) -> s -> m ()+-- 'sequenceOf_' :: 'Monad' m => 'Prism'' s (m a)     -> s -> m ()+-- @+sequenceOf_ :: Monad m => Getting (Sequenced a m) s (m a) -> s -> m ()+sequenceOf_ l = liftM skip . getSequenced #. foldMapOf l Sequenced+{-# INLINE sequenceOf_ #-}++-- | The sum of a collection of actions, generalizing 'concatOf'.+--+-- >>> asumOf both ("hello","world")+-- "helloworld"+--+-- >>> asumOf each (Nothing, Just "hello", Nothing)+-- Just "hello"+--+-- @+-- 'asum' ≡ 'asumOf' 'folded'+-- @+--+-- @+-- 'asumOf' :: 'Alternative' f => 'Getter' s (f a)     -> s -> f a+-- 'asumOf' :: 'Alternative' f => 'Fold' s (f a)       -> s -> f a+-- 'asumOf' :: 'Alternative' f => 'Lens'' s (f a)      -> s -> f a+-- 'asumOf' :: 'Alternative' f => 'Iso'' s (f a)       -> s -> f a+-- 'asumOf' :: 'Alternative' f => 'Traversal'' s (f a) -> s -> f a+-- 'asumOf' :: 'Alternative' f => 'Prism'' s (f a)     -> s -> f a+-- @+asumOf :: Alternative f => Getting (Endo (f a)) s (f a) -> s -> f a+asumOf l = foldrOf l (<|>) empty+{-# INLINE asumOf #-}++-- | The sum of a collection of actions, generalizing 'concatOf'.+--+-- >>> msumOf both ("hello","world")+-- "helloworld"+--+-- >>> msumOf each (Nothing, Just "hello", Nothing)+-- Just "hello"+--+-- @+-- 'msum' ≡ 'msumOf' 'folded'+-- @+--+-- @+-- 'msumOf' :: 'MonadPlus' m => 'Getter' s (m a)     -> s -> m a+-- 'msumOf' :: 'MonadPlus' m => 'Fold' s (m a)       -> s -> m a+-- 'msumOf' :: 'MonadPlus' m => 'Lens'' s (m a)      -> s -> m a+-- 'msumOf' :: 'MonadPlus' m => 'Iso'' s (m a)       -> s -> m a+-- 'msumOf' :: 'MonadPlus' m => 'Traversal'' s (m a) -> s -> m a+-- 'msumOf' :: 'MonadPlus' m => 'Prism'' s (m a)     -> s -> m a+-- @+msumOf :: MonadPlus m => Getting (Endo (m a)) s (m a) -> s -> m a+msumOf l = foldrOf l mplus mzero+{-# INLINE msumOf #-}++-- | Does the element occur anywhere within a given 'Fold' of the structure?+--+-- >>> elemOf both "hello" ("hello","world")+-- True+--+-- @+-- 'elem' ≡ 'elemOf' 'folded'+-- @+--+-- @+-- 'elemOf' :: 'Eq' a => 'Getter' s a     -> a -> s -> 'Bool'+-- 'elemOf' :: 'Eq' a => 'Fold' s a       -> a -> s -> 'Bool'+-- 'elemOf' :: 'Eq' a => 'Lens'' s a      -> a -> s -> 'Bool'+-- 'elemOf' :: 'Eq' a => 'Iso'' s a       -> a -> s -> 'Bool'+-- 'elemOf' :: 'Eq' a => 'Traversal'' s a -> a -> s -> 'Bool'+-- 'elemOf' :: 'Eq' a => 'Prism'' s a     -> a -> s -> 'Bool'+-- @+elemOf :: Eq a => Getting Any s a -> a -> s -> Bool+elemOf l = anyOf l . (==)+{-# INLINE elemOf #-}++-- | Does the element not occur anywhere within a given 'Fold' of the structure?+--+-- >>> notElemOf each 'd' ('a','b','c')+-- True+--+-- >>> notElemOf each 'a' ('a','b','c')+-- False+--+-- @+-- 'notElem' ≡ 'notElemOf' 'folded'+-- @+--+-- @+-- 'notElemOf' :: 'Eq' a => 'Getter' s a     -> a -> s -> 'Bool'+-- 'notElemOf' :: 'Eq' a => 'Fold' s a       -> a -> s -> 'Bool'+-- 'notElemOf' :: 'Eq' a => 'Iso'' s a       -> a -> s -> 'Bool'+-- 'notElemOf' :: 'Eq' a => 'Lens'' s a      -> a -> s -> 'Bool'+-- 'notElemOf' :: 'Eq' a => 'Traversal'' s a -> a -> s -> 'Bool'+-- 'notElemOf' :: 'Eq' a => 'Prism'' s a     -> a -> s -> 'Bool'+-- @+notElemOf :: Eq a => Getting All s a -> a -> s -> Bool+notElemOf l = allOf l . (/=)+{-# INLINE notElemOf #-}++-- | Map a function over all the targets of a 'Fold' of a container and concatenate the resulting lists.+--+-- >>> concatMapOf both (\x -> [x, x + 1]) (1,3)+-- [1,2,3,4]+--+-- @+-- 'concatMap' ≡ 'concatMapOf' 'folded'+-- @+--+-- @+-- 'concatMapOf' :: 'Getter' s a     -> (a -> [r]) -> s -> [r]+-- 'concatMapOf' :: 'Fold' s a       -> (a -> [r]) -> s -> [r]+-- 'concatMapOf' :: 'Lens'' s a      -> (a -> [r]) -> s -> [r]+-- 'concatMapOf' :: 'Iso'' s a       -> (a -> [r]) -> s -> [r]+-- 'concatMapOf' :: 'Traversal'' s a -> (a -> [r]) -> s -> [r]+-- @+concatMapOf :: Getting [r] s a -> (a -> [r]) -> s -> [r]+concatMapOf = coerce+{-# INLINE concatMapOf #-}++-- | Concatenate all of the lists targeted by a 'Fold' into a longer list.+--+-- >>> concatOf both ("pan","ama")+-- "panama"+--+-- @+-- 'concat' ≡ 'concatOf' 'folded'+-- 'concatOf' ≡ 'view'+-- @+--+-- @+-- 'concatOf' :: 'Getter' s [r]     -> s -> [r]+-- 'concatOf' :: 'Fold' s [r]       -> s -> [r]+-- 'concatOf' :: 'Iso'' s [r]       -> s -> [r]+-- 'concatOf' :: 'Lens'' s [r]      -> s -> [r]+-- 'concatOf' :: 'Traversal'' s [r] -> s -> [r]+-- @+concatOf :: Getting [r] s [r] -> s -> [r]+concatOf l = getConst #. l Const+{-# INLINE concatOf #-}+++-- | Calculate the number of targets there are for a 'Fold' in a given container.+--+-- /Note:/ This can be rather inefficient for large containers and just like 'length',+-- this will not terminate for infinite folds.+--+-- @+-- 'length' ≡ 'lengthOf' 'folded'+-- @+--+-- >>> lengthOf _1 ("hello",())+-- 1+--+-- >>> lengthOf traverse [1..10]+-- 10+--+-- >>> lengthOf (traverse.traverse) [[1,2],[3,4],[5,6]]+-- 6+--+-- @+-- 'lengthOf' ('folded' '.' 'folded') :: ('Foldable' f, 'Foldable' g) => f (g a) -> 'Int'+-- @+--+-- @+-- 'lengthOf' :: 'Getter' s a     -> s -> 'Int'+-- 'lengthOf' :: 'Fold' s a       -> s -> 'Int'+-- 'lengthOf' :: 'Lens'' s a      -> s -> 'Int'+-- 'lengthOf' :: 'Iso'' s a       -> s -> 'Int'+-- 'lengthOf' :: 'Traversal'' s a -> s -> 'Int'+-- @+lengthOf :: Getting (Endo (Endo Int)) s a -> s -> Int+lengthOf l = foldlOf' l (\a _ -> a + 1) 0+{-# INLINE lengthOf #-}++-- | Perform a safe 'head' of a 'Fold' or 'Traversal' or retrieve 'Just' the result+-- from a 'Getter' or 'Lens'.+--+-- When using a 'Traversal' as a partial 'Lens', or a 'Fold' as a partial 'Getter' this can be a convenient+-- way to extract the optional value.+--+-- Note: if you get stack overflows due to this, you may want to use 'firstOf' instead, which can deal+-- more gracefully with heavily left-biased trees. This is because '^?' works by using the+-- 'Data.Monoid.First' monoid, which can occasionally cause space leaks.+--+-- >>> Left 4 ^?_Left+-- Just 4+--+-- >>> Right 4 ^?_Left+-- Nothing+--+-- >>> "world" ^? ix 3+-- Just 'l'+--+-- >>> "world" ^? ix 20+-- Nothing+--+-- This operator works as an infix version of 'preview'.+--+-- @+-- ('^?') ≡ 'flip' 'preview'+-- @+--+-- It may be helpful to think of '^?' as having one of the following+-- more specialized types:+--+-- @+-- ('^?') :: s -> 'Getter' s a     -> 'Maybe' a+-- ('^?') :: s -> 'Fold' s a       -> 'Maybe' a+-- ('^?') :: s -> 'Lens'' s a      -> 'Maybe' a+-- ('^?') :: s -> 'Iso'' s a       -> 'Maybe' a+-- ('^?') :: s -> 'Traversal'' s a -> 'Maybe' a+-- @+(^?) :: s -> Getting (First a) s a -> Maybe a+s ^? l = getFirst (foldMapOf l (First #. Just) s)+{-# INLINE (^?) #-}++-- | Perform an *UNSAFE* 'head' of a 'Fold' or 'Traversal' assuming that it is there.+--+-- >>> Left 4 ^?! _Left+-- 4+--+-- >>> "world" ^?! ix 3+-- 'l'+--+-- @+-- ('^?!') :: s -> 'Getter' s a     -> a+-- ('^?!') :: s -> 'Fold' s a       -> a+-- ('^?!') :: s -> 'Lens'' s a      -> a+-- ('^?!') :: s -> 'Iso'' s a       -> a+-- ('^?!') :: s -> 'Traversal'' s a -> a+-- @+(^?!) :: HasCallStack => s -> Getting (Endo a) s a -> a+s ^?! l = foldrOf l const (error "(^?!): empty Fold") s+{-# INLINE (^?!) #-}++-- | Retrieve the 'First' entry of a 'Fold' or 'Traversal' or retrieve 'Just' the result+-- from a 'Getter' or 'Lens'.+--+-- The answer is computed in a manner that leaks space less than @'preview'@ or @^?'@+-- and gives you back access to the outermost 'Just' constructor more quickly, but does so+-- in a way that builds an intermediate structure, and thus may have worse+-- constant factors. This also means that it can not be used in any 'Control.Monad.Reader.MonadReader',+-- but must instead have 's' passed as its last argument, unlike 'preview'.+--+-- Note: this could been named `headOf`.+--+-- >>> firstOf traverse [1..10]+-- Just 1+--+-- >>> firstOf both (1,2)+-- Just 1+--+-- >>> firstOf ignored ()+-- Nothing+--+-- @+-- 'firstOf' :: 'Getter' s a     -> s -> 'Maybe' a+-- 'firstOf' :: 'Fold' s a       -> s -> 'Maybe' a+-- 'firstOf' :: 'Lens'' s a      -> s -> 'Maybe' a+-- 'firstOf' :: 'Iso'' s a       -> s -> 'Maybe' a+-- 'firstOf' :: 'Traversal'' s a -> s -> 'Maybe' a+-- @+firstOf :: Getting (Leftmost a) s a -> s -> Maybe a+firstOf l = getLeftmost . foldMapOf l LLeaf+{-# INLINE firstOf #-}++-- | Retrieve the 'Data.Semigroup.First' entry of a 'Fold1' or 'Traversal1' or the result from a 'Getter' or 'Lens'.+--+-- >>> first1Of traverse1 (1 :| [2..10])+-- 1+--+-- >>> first1Of both1 (1,2)+-- 1+--+-- /Note:/ this is different from '^.'.+--+-- >>> first1Of traverse1 ([1,2] :| [[3,4],[5,6]])+-- [1,2]+--+-- >>> ([1,2] :| [[3,4],[5,6]]) ^. traverse1+-- [1,2,3,4,5,6]+--+-- @+-- 'first1Of' :: 'Getter' s a      -> s -> a+-- 'first1Of' :: 'Fold1' s a       -> s -> a+-- 'first1Of' :: 'Lens'' s a       -> s -> a+-- 'first1Of' :: 'Iso'' s a        -> s -> a+-- 'first1Of' :: 'Traversal1'' s a -> s -> a+-- @+first1Of :: Getting (Semi.First a) s a -> s -> a+first1Of l = Semi.getFirst . foldMapOf l Semi.First++-- | Retrieve the 'Last' entry of a 'Fold' or 'Traversal' or retrieve 'Just' the result+-- from a 'Getter' or 'Lens'.+--+-- The answer is computed in a manner that leaks space less than @'ala' 'Last' '.' 'foldMapOf'@+-- and gives you back access to the outermost 'Just' constructor more quickly, but may have worse+-- constant factors.+--+-- >>> lastOf traverse [1..10]+-- Just 10+--+-- >>> lastOf both (1,2)+-- Just 2+--+-- >>> lastOf ignored ()+-- Nothing+--+-- @+-- 'lastOf' :: 'Getter' s a     -> s -> 'Maybe' a+-- 'lastOf' :: 'Fold' s a       -> s -> 'Maybe' a+-- 'lastOf' :: 'Lens'' s a      -> s -> 'Maybe' a+-- 'lastOf' :: 'Iso'' s a       -> s -> 'Maybe' a+-- 'lastOf' :: 'Traversal'' s a -> s -> 'Maybe' a+-- @+lastOf :: Getting (Rightmost a) s a -> s -> Maybe a+lastOf l = getRightmost . foldMapOf l RLeaf+{-# INLINE lastOf #-}++-- | Retrieve the 'Data.Semigroup.Last' entry of a 'Fold1' or 'Traversal1' or retrieve the result+-- from a 'Getter' or 'Lens'.o+--+-- >>> last1Of traverse1 (1 :| [2..10])+-- 10+--+-- >>> last1Of both1 (1,2)+-- 2+--+-- @+-- 'last1Of' :: 'Getter' s a      -> s -> 'Maybe' a+-- 'last1Of' :: 'Fold1' s a       -> s -> 'Maybe' a+-- 'last1Of' :: 'Lens'' s a       -> s -> 'Maybe' a+-- 'last1Of' :: 'Iso'' s a        -> s -> 'Maybe' a+-- 'last1Of' :: 'Traversal1'' s a -> s -> 'Maybe' a+-- @+last1Of :: Getting (Semi.Last a) s a -> s -> a+last1Of l = Semi.getLast . foldMapOf l Semi.Last++-- | Returns 'True' if this 'Fold' or 'Traversal' has no targets in the given container.+--+-- Note: 'nullOf' on a valid 'Iso', 'Lens' or 'Getter' should always return 'False'.+--+-- @+-- 'null' ≡ 'nullOf' 'folded'+-- @+--+-- This may be rather inefficient compared to the 'null' check of many containers.+--+-- >>> nullOf _1 (1,2)+-- False+--+-- >>> nullOf ignored ()+-- True+--+-- >>> nullOf traverse []+-- True+--+-- >>> nullOf (element 20) [1..10]+-- True+--+-- @+-- 'nullOf' ('folded' '.' '_1' '.' 'folded') :: ('Foldable' f, 'Foldable' g) => f (g a, b) -> 'Bool'+-- @+--+-- @+-- 'nullOf' :: 'Getter' s a     -> s -> 'Bool'+-- 'nullOf' :: 'Fold' s a       -> s -> 'Bool'+-- 'nullOf' :: 'Iso'' s a       -> s -> 'Bool'+-- 'nullOf' :: 'Lens'' s a      -> s -> 'Bool'+-- 'nullOf' :: 'Traversal'' s a -> s -> 'Bool'+-- @+nullOf :: Getting All s a -> s -> Bool+nullOf = hasn't+{-# INLINE nullOf #-}++-- | Returns 'True' if this 'Fold' or 'Traversal' has any targets in the given container.+--+-- A more \"conversational\" alias for this combinator is 'has'.+--+-- Note: 'notNullOf' on a valid 'Iso', 'Lens' or 'Getter' should always return 'True'.+--+-- @+-- 'not' '.' 'null' ≡ 'notNullOf' 'folded'+-- @+--+-- This may be rather inefficient compared to the @'not' '.' 'null'@ check of many containers.+--+-- >>> notNullOf _1 (1,2)+-- True+--+-- >>> notNullOf traverse [1..10]+-- True+--+-- >>> notNullOf folded []+-- False+--+-- >>> notNullOf (element 20) [1..10]+-- False+--+-- @+-- 'notNullOf' ('folded' '.' '_1' '.' 'folded') :: ('Foldable' f, 'Foldable' g) => f (g a, b) -> 'Bool'+-- @+--+-- @+-- 'notNullOf' :: 'Getter' s a     -> s -> 'Bool'+-- 'notNullOf' :: 'Fold' s a       -> s -> 'Bool'+-- 'notNullOf' :: 'Iso'' s a       -> s -> 'Bool'+-- 'notNullOf' :: 'Lens'' s a      -> s -> 'Bool'+-- 'notNullOf' :: 'Traversal'' s a -> s -> 'Bool'+-- @+notNullOf :: Getting Any s a -> s -> Bool+notNullOf = has+{-# INLINE notNullOf #-}++-- | Obtain the maximum element (if any) targeted by a 'Fold' or 'Traversal' safely.+--+-- Note: 'maximumOf' on a valid 'Iso', 'Lens' or 'Getter' will always return 'Just' a value.+--+-- >>> maximumOf traverse [1..10]+-- Just 10+--+-- >>> maximumOf traverse []+-- Nothing+--+-- >>> maximumOf (folded.filtered even) [1,4,3,6,7,9,2]+-- Just 6+--+-- @+-- 'maximum' ≡ 'fromMaybe' ('error' \"empty\") '.' 'maximumOf' 'folded'+-- @+--+-- In the interest of efficiency, This operation has semantics more strict than strictly necessary.+-- @'rmap' 'getMax' ('foldMapOf' l 'Max')@ has lazier semantics but could leak memory.+--+-- @+-- 'maximumOf' :: 'Ord' a => 'Getter' s a     -> s -> 'Maybe' a+-- 'maximumOf' :: 'Ord' a => 'Fold' s a       -> s -> 'Maybe' a+-- 'maximumOf' :: 'Ord' a => 'Iso'' s a       -> s -> 'Maybe' a+-- 'maximumOf' :: 'Ord' a => 'Lens'' s a      -> s -> 'Maybe' a+-- 'maximumOf' :: 'Ord' a => 'Traversal'' s a -> s -> 'Maybe' a+-- @+maximumOf :: Ord a => Getting (Endo (Endo (Maybe a))) s a -> s -> Maybe a+maximumOf l = foldlOf' l mf Nothing where+  mf Nothing y = Just $! y+  mf (Just x) y = Just $! max x y+{-# INLINE maximumOf #-}++-- | Obtain the maximum element targeted by a 'Fold1' or 'Traversal1'.+--+-- >>> maximum1Of traverse1 (1 :| [2..10])+-- 10+--+-- @+-- 'maximum1Of' :: 'Ord' a => 'Getter' s a      -> s -> a+-- 'maximum1Of' :: 'Ord' a => 'Fold1' s a       -> s -> a+-- 'maximum1Of' :: 'Ord' a => 'Iso'' s a        -> s -> a+-- 'maximum1Of' :: 'Ord' a => 'Lens'' s a       -> s -> a+-- 'maximum1Of' :: 'Ord' a => 'Traversal1'' s a -> s -> a+-- @+maximum1Of :: Ord a => Getting (Semi.Max a) s a -> s -> a+maximum1Of l = Semi.getMax . foldMapOf l Semi.Max+{-# INLINE maximum1Of #-}++-- | Obtain the minimum element (if any) targeted by a 'Fold' or 'Traversal' safely.+--+-- Note: 'minimumOf' on a valid 'Iso', 'Lens' or 'Getter' will always return 'Just' a value.+--+-- >>> minimumOf traverse [1..10]+-- Just 1+--+-- >>> minimumOf traverse []+-- Nothing+--+-- >>> minimumOf (folded.filtered even) [1,4,3,6,7,9,2]+-- Just 2+--+-- @+-- 'minimum' ≡ 'Data.Maybe.fromMaybe' ('error' \"empty\") '.' 'minimumOf' 'folded'+-- @+--+-- In the interest of efficiency, This operation has semantics more strict than strictly necessary.+-- @'rmap' 'getMin' ('foldMapOf' l 'Min')@ has lazier semantics but could leak memory.+--+--+-- @+-- 'minimumOf' :: 'Ord' a => 'Getter' s a     -> s -> 'Maybe' a+-- 'minimumOf' :: 'Ord' a => 'Fold' s a       -> s -> 'Maybe' a+-- 'minimumOf' :: 'Ord' a => 'Iso'' s a       -> s -> 'Maybe' a+-- 'minimumOf' :: 'Ord' a => 'Lens'' s a      -> s -> 'Maybe' a+-- 'minimumOf' :: 'Ord' a => 'Traversal'' s a -> s -> 'Maybe' a+-- @+minimumOf :: Ord a => Getting (Endo (Endo (Maybe a))) s a -> s -> Maybe a+minimumOf l = foldlOf' l mf Nothing where+  mf Nothing y = Just $! y+  mf (Just x) y = Just $! min x y+{-# INLINE minimumOf #-}++-- | Obtain the minimum element targeted by a 'Fold1' or 'Traversal1'.+--+-- >>> minimum1Of traverse1 (1 :| [2..10])+-- 1+--+-- @+-- 'minimum1Of' :: 'Ord' a => 'Getter' s a      -> s -> a+-- 'minimum1Of' :: 'Ord' a => 'Fold1' s a       -> s -> a+-- 'minimum1Of' :: 'Ord' a => 'Iso'' s a        -> s -> a+-- 'minimum1Of' :: 'Ord' a => 'Lens'' s a       -> s -> a+-- 'minimum1Of' :: 'Ord' a => 'Traversal1'' s a -> s -> a+-- @+minimum1Of :: Ord a => Getting (Semi.Min a) s a -> s -> a+minimum1Of l = Semi.getMin . foldMapOf l Semi.Min+{-# INLINE minimum1Of #-}++-- | Obtain the maximum element (if any) targeted by a 'Fold', 'Traversal', 'Lens', 'Iso',+-- or 'Getter' according to a user supplied 'Ordering'.+--+-- >>> maximumByOf traverse (compare `on` length) ["mustard","relish","ham"]+-- Just "mustard"+--+-- In the interest of efficiency, This operation has semantics more strict than strictly necessary.+--+-- @+-- 'Data.Foldable.maximumBy' cmp ≡ 'Data.Maybe.fromMaybe' ('error' \"empty\") '.' 'maximumByOf' 'folded' cmp+-- @+--+-- @+-- 'maximumByOf' :: 'Getter' s a     -> (a -> a -> 'Ordering') -> s -> 'Maybe' a+-- 'maximumByOf' :: 'Fold' s a       -> (a -> a -> 'Ordering') -> s -> 'Maybe' a+-- 'maximumByOf' :: 'Iso'' s a       -> (a -> a -> 'Ordering') -> s -> 'Maybe' a+-- 'maximumByOf' :: 'Lens'' s a      -> (a -> a -> 'Ordering') -> s -> 'Maybe' a+-- 'maximumByOf' :: 'Traversal'' s a -> (a -> a -> 'Ordering') -> s -> 'Maybe' a+-- @+maximumByOf :: Getting (Endo (Endo (Maybe a))) s a -> (a -> a -> Ordering) -> s -> Maybe a+maximumByOf l cmp = foldlOf' l mf Nothing where+  mf Nothing y = Just $! y+  mf (Just x) y = Just $! if cmp x y == GT then x else y+{-# INLINE maximumByOf #-}++-- | Obtain the minimum element (if any) targeted by a 'Fold', 'Traversal', 'Lens', 'Iso'+-- or 'Getter' according to a user supplied 'Ordering'.+--+-- In the interest of efficiency, This operation has semantics more strict than strictly necessary.+--+-- >>> minimumByOf traverse (compare `on` length) ["mustard","relish","ham"]+-- Just "ham"+--+-- @+-- 'minimumBy' cmp ≡ 'Data.Maybe.fromMaybe' ('error' \"empty\") '.' 'minimumByOf' 'folded' cmp+-- @+--+-- @+-- 'minimumByOf' :: 'Getter' s a     -> (a -> a -> 'Ordering') -> s -> 'Maybe' a+-- 'minimumByOf' :: 'Fold' s a       -> (a -> a -> 'Ordering') -> s -> 'Maybe' a+-- 'minimumByOf' :: 'Iso'' s a       -> (a -> a -> 'Ordering') -> s -> 'Maybe' a+-- 'minimumByOf' :: 'Lens'' s a      -> (a -> a -> 'Ordering') -> s -> 'Maybe' a+-- 'minimumByOf' :: 'Traversal'' s a -> (a -> a -> 'Ordering') -> s -> 'Maybe' a+-- @+minimumByOf :: Getting (Endo (Endo (Maybe a))) s a -> (a -> a -> Ordering) -> s -> Maybe a+minimumByOf l cmp = foldlOf' l mf Nothing where+  mf Nothing y = Just $! y+  mf (Just x) y = Just $! if cmp x y == GT then y else x+{-# INLINE minimumByOf #-}++-- | The 'findOf' function takes a 'Lens' (or 'Getter', 'Iso', 'Fold', or 'Traversal'),+-- a predicate and a structure and returns the leftmost element of the structure+-- matching the predicate, or 'Nothing' if there is no such element.+--+-- >>> findOf each even (1,3,4,6)+-- Just 4+--+-- >>> findOf folded even [1,3,5,7]+-- Nothing+--+-- @+-- 'findOf' :: 'Getter' s a     -> (a -> 'Bool') -> s -> 'Maybe' a+-- 'findOf' :: 'Fold' s a       -> (a -> 'Bool') -> s -> 'Maybe' a+-- 'findOf' :: 'Iso'' s a       -> (a -> 'Bool') -> s -> 'Maybe' a+-- 'findOf' :: 'Lens'' s a      -> (a -> 'Bool') -> s -> 'Maybe' a+-- 'findOf' :: 'Traversal'' s a -> (a -> 'Bool') -> s -> 'Maybe' a+-- @+--+-- @+-- 'Data.Foldable.find' ≡ 'findOf' 'folded'+-- 'ifindOf' l ≡ 'findOf' l '.' 'Indexed'+-- @+--+-- A simpler version that didn't permit indexing, would be:+--+-- @+-- 'findOf' :: 'Getting' ('Endo' ('Maybe' a)) s a -> (a -> 'Bool') -> s -> 'Maybe' a+-- 'findOf' l p = 'foldrOf' l (\a y -> if p a then 'Just' a else y) 'Nothing'+-- @+findOf :: Getting (Endo (Maybe a)) s a -> (a -> Bool) -> s -> Maybe a+findOf l f = foldrOf l (\a y -> if f a then Just a else y) Nothing+{-# INLINE findOf #-}++-- | The 'findMOf' function takes a 'Lens' (or 'Getter', 'Iso', 'Fold', or 'Traversal'),+-- a monadic predicate and a structure and returns in the monad the leftmost element of the structure+-- matching the predicate, or 'Nothing' if there is no such element.+--+-- >>>  findMOf each ( \x -> print ("Checking " ++ show x) >> return (even x)) (1,3,4,6)+-- "Checking 1"+-- "Checking 3"+-- "Checking 4"+-- Just 4+--+-- >>>  findMOf each ( \x -> print ("Checking " ++ show x) >> return (even x)) (1,3,5,7)+-- "Checking 1"+-- "Checking 3"+-- "Checking 5"+-- "Checking 7"+-- Nothing+--+-- @+-- 'findMOf' :: ('Monad' m, 'Getter' s a)     -> (a -> m 'Bool') -> s -> m ('Maybe' a)+-- 'findMOf' :: ('Monad' m, 'Fold' s a)       -> (a -> m 'Bool') -> s -> m ('Maybe' a)+-- 'findMOf' :: ('Monad' m, 'Iso'' s a)       -> (a -> m 'Bool') -> s -> m ('Maybe' a)+-- 'findMOf' :: ('Monad' m, 'Lens'' s a)      -> (a -> m 'Bool') -> s -> m ('Maybe' a)+-- 'findMOf' :: ('Monad' m, 'Traversal'' s a) -> (a -> m 'Bool') -> s -> m ('Maybe' a)+-- @+--+-- @+-- 'findMOf' 'folded' :: (Monad m, Foldable f) => (a -> m Bool) -> f a -> m (Maybe a)+-- 'ifindMOf' l ≡ 'findMOf' l '.' 'Indexed'+-- @+--+-- A simpler version that didn't permit indexing, would be:+--+-- @+-- 'findMOf' :: Monad m => 'Getting' ('Endo' (m ('Maybe' a))) s a -> (a -> m 'Bool') -> s -> m ('Maybe' a)+-- 'findMOf' l p = 'foldrOf' l (\a y -> p a >>= \x -> if x then return ('Just' a) else y) $ return 'Nothing'+-- @+findMOf :: Monad m => Getting (Endo (m (Maybe a))) s a -> (a -> m Bool) -> s -> m (Maybe a)+findMOf l f = foldrOf l (\a y -> f a >>= \r -> if r then return (Just a) else y) $ return Nothing+{-# INLINE findMOf #-}++-- | The 'lookupOf' function takes a 'Fold' (or 'Getter', 'Traversal',+-- 'Lens', 'Iso', etc.), a key, and a structure containing key/value pairs.+-- It returns the first value corresponding to the given key. This function+-- generalizes 'lookup' to work on an arbitrary 'Fold' instead of lists.+--+-- >>> lookupOf folded 4 [(2, 'a'), (4, 'b'), (4, 'c')]+-- Just 'b'+--+-- >>> lookupOf each 2 [(2, 'a'), (4, 'b'), (4, 'c')]+-- Just 'a'+--+-- @+-- 'lookupOf' :: 'Eq' k => 'Fold' s (k,v) -> k -> s -> 'Maybe' v+-- @+lookupOf :: Eq k => Getting (Endo (Maybe v)) s (k,v) -> k -> s -> Maybe v+lookupOf l k = foldrOf l (\(k',v) next -> if k == k' then Just v else next) Nothing+{-# INLINE lookupOf #-}++-- | A variant of 'foldrOf' that has no base case and thus may only be applied+-- to lenses and structures such that the 'Lens' views at least one element of+-- the structure.+--+-- >>> foldr1Of each (+) (1,2,3,4)+-- 10+--+-- @+-- 'foldr1Of' l f ≡ 'Prelude.foldr1' f '.' 'toListOf' l+-- 'Data.Foldable.foldr1' ≡ 'foldr1Of' 'folded'+-- @+--+-- @+-- 'foldr1Of' :: 'Getter' s a     -> (a -> a -> a) -> s -> a+-- 'foldr1Of' :: 'Fold' s a       -> (a -> a -> a) -> s -> a+-- 'foldr1Of' :: 'Iso'' s a       -> (a -> a -> a) -> s -> a+-- 'foldr1Of' :: 'Lens'' s a      -> (a -> a -> a) -> s -> a+-- 'foldr1Of' :: 'Traversal'' s a -> (a -> a -> a) -> s -> a+-- @+foldr1Of :: HasCallStack => Getting (Endo (Maybe a)) s a -> (a -> a -> a) -> s -> a+-- See: NOTE: [Inlining and arity]+foldr1Of l f = fromMaybe (error "foldr1Of: empty structure")+             . foldrOf l mf Nothing where+  mf x my = Just $ case my of+    Nothing -> x+    Just y -> f x y+{-# INLINE foldr1Of #-}++-- | A variant of 'foldlOf' that has no base case and thus may only be applied to lenses and structures such+-- that the 'Lens' views at least one element of the structure.+--+-- >>> foldl1Of each (+) (1,2,3,4)+-- 10+--+-- @+-- 'foldl1Of' l f ≡ 'Prelude.foldl1' f '.' 'toListOf' l+-- 'Data.Foldable.foldl1' ≡ 'foldl1Of' 'folded'+-- @+--+-- @+-- 'foldl1Of' :: 'Getter' s a     -> (a -> a -> a) -> s -> a+-- 'foldl1Of' :: 'Fold' s a       -> (a -> a -> a) -> s -> a+-- 'foldl1Of' :: 'Iso'' s a       -> (a -> a -> a) -> s -> a+-- 'foldl1Of' :: 'Lens'' s a      -> (a -> a -> a) -> s -> a+-- 'foldl1Of' :: 'Traversal'' s a -> (a -> a -> a) -> s -> a+-- @+foldl1Of :: HasCallStack => Getting (Dual (Endo (Maybe a))) s a -> (a -> a -> a) -> s -> a+-- See: NOTE: [Inlining and arity]+foldl1Of l f = fromMaybe (error "foldl1Of: empty structure") . foldlOf l mf Nothing where+  mf mx y = Just $ case mx of+    Nothing -> y+    Just x  -> f x y+{-# INLINE foldl1Of #-}++-- | Strictly fold right over the elements of a structure.+--+-- @+-- 'Data.Foldable.foldr'' ≡ 'foldrOf'' 'folded'+-- @+--+-- @+-- 'foldrOf'' :: 'Getter' s a     -> (a -> r -> r) -> r -> s -> r+-- 'foldrOf'' :: 'Fold' s a       -> (a -> r -> r) -> r -> s -> r+-- 'foldrOf'' :: 'Iso'' s a       -> (a -> r -> r) -> r -> s -> r+-- 'foldrOf'' :: 'Lens'' s a      -> (a -> r -> r) -> r -> s -> r+-- 'foldrOf'' :: 'Traversal'' s a -> (a -> r -> r) -> r -> s -> r+-- @+foldrOf' :: Getting (Dual (Endo (Endo r))) s a -> (a -> r -> r) -> r -> s -> r+-- See: NOTE: [Inlining and arity]+foldrOf' l f z0 = \xs -> foldlOf l f' (Endo id) xs `appEndo` z0+  where f' (Endo k) x = Endo $ \ z -> k $! f x z+{-# INLINE foldrOf' #-}++-- | Fold over the elements of a structure, associating to the left, but strictly.+--+-- @+-- 'Data.Foldable.foldl'' ≡ 'foldlOf'' 'folded'+-- @+--+-- @+-- 'foldlOf'' :: 'Getter' s a     -> (r -> a -> r) -> r -> s -> r+-- 'foldlOf'' :: 'Fold' s a       -> (r -> a -> r) -> r -> s -> r+-- 'foldlOf'' :: 'Iso'' s a       -> (r -> a -> r) -> r -> s -> r+-- 'foldlOf'' :: 'Lens'' s a      -> (r -> a -> r) -> r -> s -> r+-- 'foldlOf'' :: 'Traversal'' s a -> (r -> a -> r) -> r -> s -> r+-- @+foldlOf' :: Getting (Endo (Endo r)) s a -> (r -> a -> r) -> r -> s -> r+-- See: NOTE: [Inlining and arity]+foldlOf' l f z0 = \xs -> foldrOf l f' (Endo id) xs `appEndo` z0+  where f' x (Endo k) = Endo $ \z -> k $! f z x+{-# INLINE foldlOf' #-}++-- | A variant of 'foldrOf'' that has no base case and thus may only be applied+-- to folds and structures such that the fold views at least one element of the+-- structure.+--+-- @+-- 'foldr1Of' l f ≡ 'Prelude.foldr1' f '.' 'toListOf' l+-- @+--+-- @+-- 'foldr1Of'' :: 'Getter' s a     -> (a -> a -> a) -> s -> a+-- 'foldr1Of'' :: 'Fold' s a       -> (a -> a -> a) -> s -> a+-- 'foldr1Of'' :: 'Iso'' s a       -> (a -> a -> a) -> s -> a+-- 'foldr1Of'' :: 'Lens'' s a      -> (a -> a -> a) -> s -> a+-- 'foldr1Of'' :: 'Traversal'' s a -> (a -> a -> a) -> s -> a+-- @+foldr1Of' :: HasCallStack => Getting (Dual (Endo (Endo (Maybe a)))) s a -> (a -> a -> a) -> s -> a+-- See: NOTE: [Inlining and arity]+foldr1Of' l f = fromMaybe (error "foldr1Of': empty structure") . foldrOf' l mf Nothing where+  mf x Nothing = Just $! x+  mf x (Just y) = Just $! f x y+{-# INLINE foldr1Of' #-}++-- | A variant of 'foldlOf'' that has no base case and thus may only be applied+-- to folds and structures such that the fold views at least one element of+-- the structure.+--+-- @+-- 'foldl1Of'' l f ≡ 'Data.List.foldl1'' f '.' 'toListOf' l+-- @+--+-- @+-- 'foldl1Of'' :: 'Getter' s a     -> (a -> a -> a) -> s -> a+-- 'foldl1Of'' :: 'Fold' s a       -> (a -> a -> a) -> s -> a+-- 'foldl1Of'' :: 'Iso'' s a       -> (a -> a -> a) -> s -> a+-- 'foldl1Of'' :: 'Lens'' s a      -> (a -> a -> a) -> s -> a+-- 'foldl1Of'' :: 'Traversal'' s a -> (a -> a -> a) -> s -> a+-- @+foldl1Of' :: HasCallStack => Getting (Endo (Endo (Maybe a))) s a -> (a -> a -> a) -> s -> a+-- See: NOTE: [Inlining and arity]+foldl1Of' l f = fromMaybe (error "foldl1Of': empty structure") . foldlOf' l mf Nothing where+  mf Nothing y = Just $! y+  mf (Just x) y = Just $! f x y+{-# INLINE foldl1Of' #-}++-- | Monadic fold over the elements of a structure, associating to the right,+-- i.e. from right to left.+--+-- @+-- 'Data.Foldable.foldrM' ≡ 'foldrMOf' 'folded'+-- @+--+-- @+-- 'foldrMOf' :: 'Monad' m => 'Getter' s a     -> (a -> r -> m r) -> r -> s -> m r+-- 'foldrMOf' :: 'Monad' m => 'Fold' s a       -> (a -> r -> m r) -> r -> s -> m r+-- 'foldrMOf' :: 'Monad' m => 'Iso'' s a       -> (a -> r -> m r) -> r -> s -> m r+-- 'foldrMOf' :: 'Monad' m => 'Lens'' s a      -> (a -> r -> m r) -> r -> s -> m r+-- 'foldrMOf' :: 'Monad' m => 'Traversal'' s a -> (a -> r -> m r) -> r -> s -> m r+-- @+foldrMOf :: Monad m+         => Getting (Dual (Endo (r -> m r))) s a+         -> (a -> r -> m r) -> r -> s -> m r+-- See: NOTE: [Inlining and arity]+foldrMOf l f z0 = \xs -> foldlOf l f' return xs z0+  where f' k x z = f x z >>= k+{-# INLINE foldrMOf #-}++-- | Monadic fold over the elements of a structure, associating to the left,+-- i.e. from left to right.+--+-- @+-- 'Data.Foldable.foldlM' ≡ 'foldlMOf' 'folded'+-- @+--+-- @+-- 'foldlMOf' :: 'Monad' m => 'Getter' s a     -> (r -> a -> m r) -> r -> s -> m r+-- 'foldlMOf' :: 'Monad' m => 'Fold' s a       -> (r -> a -> m r) -> r -> s -> m r+-- 'foldlMOf' :: 'Monad' m => 'Iso'' s a       -> (r -> a -> m r) -> r -> s -> m r+-- 'foldlMOf' :: 'Monad' m => 'Lens'' s a      -> (r -> a -> m r) -> r -> s -> m r+-- 'foldlMOf' :: 'Monad' m => 'Traversal'' s a -> (r -> a -> m r) -> r -> s -> m r+-- @+foldlMOf :: Monad m+         => Getting (Endo (r -> m r)) s a+         -> (r -> a -> m r) -> r -> s -> m r+-- See: NOTE: [Inlining and arity]+foldlMOf l f z0 = \xs -> foldrOf l f' return xs z0+  where f' x k z = f z x >>= k+{-# INLINE foldlMOf #-}++-- NOTE: [Inlining and arity]+-- ~~~~~~~~~~~~~~~~~~~~~~~~~~+--+-- GHC uses the following inlining heuristic: a function body is inlined if+-- all its arguments on the LHS are applied. So the following two definitions+-- are not equivalent from the inliner's PoV:+--+-- > foldlOf' l f z0 xs = ...+-- > foldlOf' l f z0 = \xs -> ...+--+-- GHC will be less eager to inline the first one and this results in+-- worse code. For example, a simple list summation using `sumOf` will be 8x slower+-- with the first version.+++-- | Check to see if this 'Fold' or 'Traversal' matches 1 or more entries.+--+-- >>> has (element 0) []+-- False+--+-- >>> has _Left (Left 12)+-- True+--+-- >>> has _Right (Left 12)+-- False+--+-- This will always return 'True' for a 'Lens' or 'Getter'.+--+-- >>> has _1 ("hello","world")+-- True+--+-- @+-- 'has' :: 'Getter' s a     -> s -> 'Bool'+-- 'has' :: 'Fold' s a       -> s -> 'Bool'+-- 'has' :: 'Iso'' s a       -> s -> 'Bool'+-- 'has' :: 'Lens'' s a      -> s -> 'Bool'+-- 'has' :: 'Traversal'' s a -> s -> 'Bool'+-- @+has :: Getting Any s a -> s -> Bool+has l = getAny #. foldMapOf l (\_ -> Any True)+{-# INLINE has #-}++++-- | Check to see if this 'Fold' or 'Traversal' has no matches.+--+-- >>> hasn't _Left (Right 12)+-- True+--+-- >>> hasn't _Left (Left 12)+-- False+hasn't :: Getting All s a -> s -> Bool+hasn't l = getAll #. foldMapOf l (\_ -> All False)+{-# INLINE hasn't #-}++------------------------------------------------------------------------------+-- Pre+------------------------------------------------------------------------------++-- | This converts a 'Fold' to a 'IndexPreservingGetter' that returns the first element, if it+-- exists, as a 'Maybe'.+--+-- @+-- 'pre' :: 'Getter' s a     -> 'IndexPreservingGetter' s ('Maybe' a)+-- 'pre' :: 'Fold' s a       -> 'IndexPreservingGetter' s ('Maybe' a)+-- 'pre' :: 'Traversal'' s a -> 'IndexPreservingGetter' s ('Maybe' a)+-- 'pre' :: 'Lens'' s a      -> 'IndexPreservingGetter' s ('Maybe' a)+-- 'pre' :: 'Iso'' s a       -> 'IndexPreservingGetter' s ('Maybe' a)+-- 'pre' :: 'Prism'' s a     -> 'IndexPreservingGetter' s ('Maybe' a)+-- @+pre :: Getting (First a) s a -> IndexPreservingGetter s (Maybe a)+pre l = dimap (getFirst . getConst #. l (Const #. First #. Just)) phantom+{-# INLINE pre #-}++-- | This converts an 'IndexedFold' to an 'IndexPreservingGetter' that returns the first index+-- and element, if they exist, as a 'Maybe'.+--+-- @+-- 'ipre' :: 'IndexedGetter' i s a     -> 'IndexPreservingGetter' s ('Maybe' (i, a))+-- 'ipre' :: 'IndexedFold' i s a       -> 'IndexPreservingGetter' s ('Maybe' (i, a))+-- 'ipre' :: 'IndexedTraversal'' i s a -> 'IndexPreservingGetter' s ('Maybe' (i, a))+-- 'ipre' :: 'IndexedLens'' i s a      -> 'IndexPreservingGetter' s ('Maybe' (i, a))+-- @+ipre :: IndexedGetting i (First (i, a)) s a -> IndexPreservingGetter s (Maybe (i, a))+ipre l = dimap (getFirst . getConst #. l (Indexed $ \i a -> Const (First (Just (i, a))))) phantom+{-# INLINE ipre #-}++------------------------------------------------------------------------------+-- Preview+------------------------------------------------------------------------------++-- | Retrieve the first value targeted by a 'Fold' or 'Traversal' (or 'Just' the result+-- from a 'Getter' or 'Lens'). See also 'firstOf' and '^?', which are similar with+-- some subtle differences (explained below).+--+-- @+-- 'Data.Maybe.listToMaybe' '.' 'toList' ≡ 'preview' 'folded'+-- @+--+-- @+-- 'preview' = 'view' '.' 'pre'+-- @+--+--+-- Unlike '^?', this function uses a+-- 'Control.Monad.Reader.MonadReader' to read the value to be focused in on.+-- This allows one to pass the value as the last argument by using the+-- 'Control.Monad.Reader.MonadReader' instance for @(->) s@+-- However, it may also be used as part of some deeply nested transformer stack.+--+-- 'preview' uses a monoidal value to obtain the result.+-- This means that it generally has good performance, but can occasionally cause space leaks+-- or even stack overflows on some data types.+-- There is another function, 'firstOf', which avoids these issues at the cost of+-- a slight constant performance cost and a little less flexibility.+--+-- It may be helpful to think of 'preview' as having one of the following+-- more specialized types:+--+-- @+-- 'preview' :: 'Getter' s a     -> s -> 'Maybe' a+-- 'preview' :: 'Fold' s a       -> s -> 'Maybe' a+-- 'preview' :: 'Lens'' s a      -> s -> 'Maybe' a+-- 'preview' :: 'Iso'' s a       -> s -> 'Maybe' a+-- 'preview' :: 'Traversal'' s a -> s -> 'Maybe' a+-- @+--+--+-- @+-- 'preview' :: 'MonadReader' s m => 'Getter' s a     -> m ('Maybe' a)+-- 'preview' :: 'MonadReader' s m => 'Fold' s a       -> m ('Maybe' a)+-- 'preview' :: 'MonadReader' s m => 'Lens'' s a      -> m ('Maybe' a)+-- 'preview' :: 'MonadReader' s m => 'Iso'' s a       -> m ('Maybe' a)+-- 'preview' :: 'MonadReader' s m => 'Traversal'' s a -> m ('Maybe' a)+--+-- @+preview :: MonadReader s m => Getting (First a) s a -> m (Maybe a)+preview l = asks (getFirst #. foldMapOf l (First #. Just))+{-# INLINE preview #-}++-- | Retrieve the first index and value targeted by a 'Fold' or 'Traversal' (or 'Just' the result+-- from a 'Getter' or 'Lens'). See also ('^@?').+--+-- @+-- 'ipreview' = 'view' '.' 'ipre'+-- @+--+-- This is usually applied in the 'Control.Monad.Reader.Reader'+-- 'Control.Monad.Monad' @(->) s@.+--+-- @+-- 'ipreview' :: 'IndexedGetter' i s a     -> s -> 'Maybe' (i, a)+-- 'ipreview' :: 'IndexedFold' i s a       -> s -> 'Maybe' (i, a)+-- 'ipreview' :: 'IndexedLens'' i s a      -> s -> 'Maybe' (i, a)+-- 'ipreview' :: 'IndexedTraversal'' i s a -> s -> 'Maybe' (i, a)+-- @+--+-- However, it may be useful to think of its full generality when working with+-- a 'Control.Monad.Monad' transformer stack:+--+-- @+-- 'ipreview' :: 'MonadReader' s m => 'IndexedGetter' s a     -> m ('Maybe' (i, a))+-- 'ipreview' :: 'MonadReader' s m => 'IndexedFold' s a       -> m ('Maybe' (i, a))+-- 'ipreview' :: 'MonadReader' s m => 'IndexedLens'' s a      -> m ('Maybe' (i, a))+-- 'ipreview' :: 'MonadReader' s m => 'IndexedTraversal'' s a -> m ('Maybe' (i, a))+-- @+ipreview :: MonadReader s m => IndexedGetting i (First (i, a)) s a -> m (Maybe (i, a))+ipreview l = asks (getFirst #. ifoldMapOf l (\i a -> First (Just (i, a))))+{-# INLINE ipreview #-}++-- | Retrieve a function of the first value targeted by a 'Fold' or+-- 'Traversal' (or 'Just' the result from a 'Getter' or 'Lens').+--+-- This is usually applied in the 'Control.Monad.Reader.Reader'+-- 'Control.Monad.Monad' @(->) s@.++-- @+-- 'previews' = 'views' '.' 'pre'+-- @+--+-- @+-- 'previews' :: 'Getter' s a     -> (a -> r) -> s -> 'Maybe' r+-- 'previews' :: 'Fold' s a       -> (a -> r) -> s -> 'Maybe' r+-- 'previews' :: 'Lens'' s a      -> (a -> r) -> s -> 'Maybe' r+-- 'previews' :: 'Iso'' s a       -> (a -> r) -> s -> 'Maybe' r+-- 'previews' :: 'Traversal'' s a -> (a -> r) -> s -> 'Maybe' r+-- @+--+-- However, it may be useful to think of its full generality when working with+-- a 'Monad' transformer stack:+--+-- @+-- 'previews' :: 'MonadReader' s m => 'Getter' s a     -> (a -> r) -> m ('Maybe' r)+-- 'previews' :: 'MonadReader' s m => 'Fold' s a       -> (a -> r) -> m ('Maybe' r)+-- 'previews' :: 'MonadReader' s m => 'Lens'' s a      -> (a -> r) -> m ('Maybe' r)+-- 'previews' :: 'MonadReader' s m => 'Iso'' s a       -> (a -> r) -> m ('Maybe' r)+-- 'previews' :: 'MonadReader' s m => 'Traversal'' s a -> (a -> r) -> m ('Maybe' r)+-- @+previews :: MonadReader s m => Getting (First r) s a -> (a -> r) -> m (Maybe r)+previews l f = asks (getFirst . foldMapOf l (First #. Just . f))+{-# INLINE previews #-}++-- | Retrieve a function of the first index and value targeted by an 'IndexedFold' or+-- 'IndexedTraversal' (or 'Just' the result from an 'IndexedGetter' or 'IndexedLens').+-- See also ('^@?').+--+-- @+-- 'ipreviews' = 'views' '.' 'ipre'+-- @+--+-- This is usually applied in the 'Control.Monad.Reader.Reader'+-- 'Control.Monad.Monad' @(->) s@.+--+-- @+-- 'ipreviews' :: 'IndexedGetter' i s a     -> (i -> a -> r) -> s -> 'Maybe' r+-- 'ipreviews' :: 'IndexedFold' i s a       -> (i -> a -> r) -> s -> 'Maybe' r+-- 'ipreviews' :: 'IndexedLens'' i s a      -> (i -> a -> r) -> s -> 'Maybe' r+-- 'ipreviews' :: 'IndexedTraversal'' i s a -> (i -> a -> r) -> s -> 'Maybe' r+-- @+--+-- However, it may be useful to think of its full generality when working with+-- a 'Control.Monad.Monad' transformer stack:+--+-- @+-- 'ipreviews' :: 'MonadReader' s m => 'IndexedGetter' i s a     -> (i -> a -> r) -> m ('Maybe' r)+-- 'ipreviews' :: 'MonadReader' s m => 'IndexedFold' i s a       -> (i -> a -> r) -> m ('Maybe' r)+-- 'ipreviews' :: 'MonadReader' s m => 'IndexedLens'' i s a      -> (i -> a -> r) -> m ('Maybe' r)+-- 'ipreviews' :: 'MonadReader' s m => 'IndexedTraversal'' i s a -> (i -> a -> r) -> m ('Maybe' r)+-- @+ipreviews :: MonadReader s m => IndexedGetting i (First r) s a -> (i -> a -> r) -> m (Maybe r)+ipreviews l f = asks (getFirst . ifoldMapOf l (\i -> First #. Just . f i))+{-# INLINE ipreviews #-}++------------------------------------------------------------------------------+-- Preuse+------------------------------------------------------------------------------++-- | Retrieve the first value targeted by a 'Fold' or 'Traversal' (or 'Just' the result+-- from a 'Getter' or 'Lens') into the current state.+--+-- @+-- 'preuse' = 'use' '.' 'pre'+-- @+--+-- @+-- 'preuse' :: 'MonadState' s m => 'Getter' s a     -> m ('Maybe' a)+-- 'preuse' :: 'MonadState' s m => 'Fold' s a       -> m ('Maybe' a)+-- 'preuse' :: 'MonadState' s m => 'Lens'' s a      -> m ('Maybe' a)+-- 'preuse' :: 'MonadState' s m => 'Iso'' s a       -> m ('Maybe' a)+-- 'preuse' :: 'MonadState' s m => 'Traversal'' s a -> m ('Maybe' a)+-- @+preuse :: MonadState s m => Getting (First a) s a -> m (Maybe a)+preuse l = gets (preview l)+{-# INLINE preuse #-}++-- | Retrieve the first index and value targeted by an 'IndexedFold' or 'IndexedTraversal' (or 'Just' the index+-- and result from an 'IndexedGetter' or 'IndexedLens') into the current state.+--+-- @+-- 'ipreuse' = 'use' '.' 'ipre'+-- @+--+-- @+-- 'ipreuse' :: 'MonadState' s m => 'IndexedGetter' i s a     -> m ('Maybe' (i, a))+-- 'ipreuse' :: 'MonadState' s m => 'IndexedFold' i s a       -> m ('Maybe' (i, a))+-- 'ipreuse' :: 'MonadState' s m => 'IndexedLens'' i s a      -> m ('Maybe' (i, a))+-- 'ipreuse' :: 'MonadState' s m => 'IndexedTraversal'' i s a -> m ('Maybe' (i, a))+-- @+ipreuse :: MonadState s m => IndexedGetting i (First (i, a)) s a -> m (Maybe (i, a))+ipreuse l = gets (ipreview l)+{-# INLINE ipreuse #-}++-- | Retrieve a function of the first value targeted by a 'Fold' or+-- 'Traversal' (or 'Just' the result from a 'Getter' or 'Lens') into the current state.+--+-- @+-- 'preuses' = 'uses' '.' 'pre'+-- @+--+-- @+-- 'preuses' :: 'MonadState' s m => 'Getter' s a     -> (a -> r) -> m ('Maybe' r)+-- 'preuses' :: 'MonadState' s m => 'Fold' s a       -> (a -> r) -> m ('Maybe' r)+-- 'preuses' :: 'MonadState' s m => 'Lens'' s a      -> (a -> r) -> m ('Maybe' r)+-- 'preuses' :: 'MonadState' s m => 'Iso'' s a       -> (a -> r) -> m ('Maybe' r)+-- 'preuses' :: 'MonadState' s m => 'Traversal'' s a -> (a -> r) -> m ('Maybe' r)+-- @+preuses :: MonadState s m => Getting (First r) s a -> (a -> r) -> m (Maybe r)+preuses l f = gets (previews l f)+{-# INLINE preuses #-}++-- | Retrieve a function of the first index and value targeted by an 'IndexedFold' or+-- 'IndexedTraversal' (or a function of 'Just' the index and result from an 'IndexedGetter'+-- or 'IndexedLens') into the current state.+--+-- @+-- 'ipreuses' = 'uses' '.' 'ipre'+-- @+--+-- @+-- 'ipreuses' :: 'MonadState' s m => 'IndexedGetter' i s a     -> (i -> a -> r) -> m ('Maybe' r)+-- 'ipreuses' :: 'MonadState' s m => 'IndexedFold' i s a       -> (i -> a -> r) -> m ('Maybe' r)+-- 'ipreuses' :: 'MonadState' s m => 'IndexedLens'' i s a      -> (i -> a -> r) -> m ('Maybe' r)+-- 'ipreuses' :: 'MonadState' s m => 'IndexedTraversal'' i s a -> (i -> a -> r) -> m ('Maybe' r)+-- @+ipreuses :: MonadState s m => IndexedGetting i (First r) s a -> (i -> a -> r) -> m (Maybe r)+ipreuses l f = gets (ipreviews l f)+{-# INLINE ipreuses #-}++------------------------------------------------------------------------------+-- Profunctors+------------------------------------------------------------------------------+++-- | This allows you to 'Control.Traversable.traverse' the elements of a pretty much any 'LensLike' construction in the opposite order.+--+-- This will preserve indexes on 'Indexed' types and will give you the elements of a (finite) 'Fold' or 'Traversal' in the opposite order.+--+-- This has no practical impact on a 'Getter', 'Setter', 'Lens' or 'Iso'.+--+-- /NB:/ To write back through an 'Iso', you want to use 'Control.Lens.Isomorphic.from'.+-- Similarly, to write back through an 'Prism', you want to use 'Control.Lens.Review.re'.+backwards :: (Profunctor p, Profunctor q) => Optical p q (Backwards f) s t a b -> Optical p q f s t a b+backwards l f = forwards #. l (Backwards #. f)+{-# INLINE backwards #-}++------------------------------------------------------------------------------+-- Indexed Folds+------------------------------------------------------------------------------++-- | Fold an 'IndexedFold' or 'IndexedTraversal' by mapping indices and values to an arbitrary 'Monoid' with access+-- to the @i@.+--+-- When you don't need access to the index then 'foldMapOf' is more flexible in what it accepts.+--+-- @+-- 'foldMapOf' l ≡ 'ifoldMapOf' l '.' 'const'+-- @+--+-- @+-- 'ifoldMapOf' ::             'IndexedGetter' i s a     -> (i -> a -> m) -> s -> m+-- 'ifoldMapOf' :: 'Monoid' m => 'IndexedFold' i s a       -> (i -> a -> m) -> s -> m+-- 'ifoldMapOf' ::             'IndexedLens'' i s a      -> (i -> a -> m) -> s -> m+-- 'ifoldMapOf' :: 'Monoid' m => 'IndexedTraversal'' i s a -> (i -> a -> m) -> s -> m+-- @+--+ifoldMapOf :: IndexedGetting i m s a -> (i -> a -> m) -> s -> m+ifoldMapOf = coerce+{-# INLINE ifoldMapOf #-}++-- | Right-associative fold of parts of a structure that are viewed through an 'IndexedFold' or 'IndexedTraversal' with+-- access to the @i@.+--+-- When you don't need access to the index then 'foldrOf' is more flexible in what it accepts.+--+-- @+-- 'foldrOf' l ≡ 'ifoldrOf' l '.' 'const'+-- @+--+-- @+-- 'ifoldrOf' :: 'IndexedGetter' i s a     -> (i -> a -> r -> r) -> r -> s -> r+-- 'ifoldrOf' :: 'IndexedFold' i s a       -> (i -> a -> r -> r) -> r -> s -> r+-- 'ifoldrOf' :: 'IndexedLens'' i s a      -> (i -> a -> r -> r) -> r -> s -> r+-- 'ifoldrOf' :: 'IndexedTraversal'' i s a -> (i -> a -> r -> r) -> r -> s -> r+-- @+ifoldrOf :: IndexedGetting i (Endo r) s a -> (i -> a -> r -> r) -> r -> s -> r+ifoldrOf l f z = flip appEndo z . getConst #. l (Const #. Endo #. Indexed f)+{-# INLINE ifoldrOf #-}++-- | Left-associative fold of the parts of a structure that are viewed through an 'IndexedFold' or 'IndexedTraversal' with+-- access to the @i@.+--+-- When you don't need access to the index then 'foldlOf' is more flexible in what it accepts.+--+-- @+-- 'foldlOf' l ≡ 'ifoldlOf' l '.' 'const'+-- @+--+-- @+-- 'ifoldlOf' :: 'IndexedGetter' i s a     -> (i -> r -> a -> r) -> r -> s -> r+-- 'ifoldlOf' :: 'IndexedFold' i s a       -> (i -> r -> a -> r) -> r -> s -> r+-- 'ifoldlOf' :: 'IndexedLens'' i s a      -> (i -> r -> a -> r) -> r -> s -> r+-- 'ifoldlOf' :: 'IndexedTraversal'' i s a -> (i -> r -> a -> r) -> r -> s -> r+-- @+ifoldlOf :: IndexedGetting i (Dual (Endo r)) s a -> (i -> r -> a -> r) -> r -> s -> r+ifoldlOf l f z = (flip appEndo z .# getDual) `rmap` ifoldMapOf l (\i -> Dual #. Endo #. flip (f i))+{-# INLINE ifoldlOf #-}++-- | Return whether or not any element viewed through an 'IndexedFold' or 'IndexedTraversal'+-- satisfy a predicate, with access to the @i@.+--+-- When you don't need access to the index then 'anyOf' is more flexible in what it accepts.+--+-- @+-- 'anyOf' l ≡ 'ianyOf' l '.' 'const'+-- @+--+-- @+-- 'ianyOf' :: 'IndexedGetter' i s a     -> (i -> a -> 'Bool') -> s -> 'Bool'+-- 'ianyOf' :: 'IndexedFold' i s a       -> (i -> a -> 'Bool') -> s -> 'Bool'+-- 'ianyOf' :: 'IndexedLens'' i s a      -> (i -> a -> 'Bool') -> s -> 'Bool'+-- 'ianyOf' :: 'IndexedTraversal'' i s a -> (i -> a -> 'Bool') -> s -> 'Bool'+-- @+ianyOf :: IndexedGetting i Any s a -> (i -> a -> Bool) -> s -> Bool+ianyOf = coerce+{-# INLINE ianyOf #-}++-- | Return whether or not all elements viewed through an 'IndexedFold' or 'IndexedTraversal'+-- satisfy a predicate, with access to the @i@.+--+-- When you don't need access to the index then 'allOf' is more flexible in what it accepts.+--+-- @+-- 'allOf' l ≡ 'iallOf' l '.' 'const'+-- @+--+-- @+-- 'iallOf' :: 'IndexedGetter' i s a     -> (i -> a -> 'Bool') -> s -> 'Bool'+-- 'iallOf' :: 'IndexedFold' i s a       -> (i -> a -> 'Bool') -> s -> 'Bool'+-- 'iallOf' :: 'IndexedLens'' i s a      -> (i -> a -> 'Bool') -> s -> 'Bool'+-- 'iallOf' :: 'IndexedTraversal'' i s a -> (i -> a -> 'Bool') -> s -> 'Bool'+-- @+iallOf :: IndexedGetting i All s a -> (i -> a -> Bool) -> s -> Bool+iallOf = coerce+{-# INLINE iallOf #-}++-- | Return whether or not none of the elements viewed through an 'IndexedFold' or 'IndexedTraversal'+-- satisfy a predicate, with access to the @i@.+--+-- When you don't need access to the index then 'noneOf' is more flexible in what it accepts.+--+-- @+-- 'noneOf' l ≡ 'inoneOf' l '.' 'const'+-- @+--+-- @+-- 'inoneOf' :: 'IndexedGetter' i s a     -> (i -> a -> 'Bool') -> s -> 'Bool'+-- 'inoneOf' :: 'IndexedFold' i s a       -> (i -> a -> 'Bool') -> s -> 'Bool'+-- 'inoneOf' :: 'IndexedLens'' i s a      -> (i -> a -> 'Bool') -> s -> 'Bool'+-- 'inoneOf' :: 'IndexedTraversal'' i s a -> (i -> a -> 'Bool') -> s -> 'Bool'+-- @+inoneOf :: IndexedGetting i Any s a -> (i -> a -> Bool) -> s -> Bool+inoneOf l f = not . ianyOf l f+{-# INLINE inoneOf #-}++-- | Traverse the targets of an 'IndexedFold' or 'IndexedTraversal' with access to the @i@, discarding the results.+--+-- When you don't need access to the index then 'traverseOf_' is more flexible in what it accepts.+--+-- @+-- 'traverseOf_' l ≡ 'Control.Lens.Traversal.itraverseOf' l '.' 'const'+-- @+--+-- @+-- 'itraverseOf_' :: 'Functor' f     => 'IndexedGetter' i s a     -> (i -> a -> f r) -> s -> f ()+-- 'itraverseOf_' :: 'Applicative' f => 'IndexedFold' i s a       -> (i -> a -> f r) -> s -> f ()+-- 'itraverseOf_' :: 'Functor' f     => 'IndexedLens'' i s a      -> (i -> a -> f r) -> s -> f ()+-- 'itraverseOf_' :: 'Applicative' f => 'IndexedTraversal'' i s a -> (i -> a -> f r) -> s -> f ()+-- @+itraverseOf_ :: Functor f => IndexedGetting i (Traversed r f) s a -> (i -> a -> f r) -> s -> f ()+itraverseOf_ l f = void . getTraversed #. getConst #. l (Const #. Traversed #. Indexed f)+{-# INLINE itraverseOf_ #-}++-- | Traverse the targets of an 'IndexedFold' or 'IndexedTraversal' with access to the index, discarding the results+-- (with the arguments flipped).+--+-- @+-- 'iforOf_' ≡ 'flip' '.' 'itraverseOf_'+-- @+--+-- When you don't need access to the index then 'forOf_' is more flexible in what it accepts.+--+-- @+-- 'forOf_' l a ≡ 'iforOf_' l a '.' 'const'+-- @+--+-- @+-- 'iforOf_' :: 'Functor' f     => 'IndexedGetter' i s a     -> s -> (i -> a -> f r) -> f ()+-- 'iforOf_' :: 'Applicative' f => 'IndexedFold' i s a       -> s -> (i -> a -> f r) -> f ()+-- 'iforOf_' :: 'Functor' f     => 'IndexedLens'' i s a      -> s -> (i -> a -> f r) -> f ()+-- 'iforOf_' :: 'Applicative' f => 'IndexedTraversal'' i s a -> s -> (i -> a -> f r) -> f ()+-- @+iforOf_ :: Functor f => IndexedGetting i (Traversed r f) s a -> s -> (i -> a -> f r) -> f ()+iforOf_ = flip . itraverseOf_+{-# INLINE iforOf_ #-}++-- | Run monadic actions for each target of an 'IndexedFold' or 'IndexedTraversal' with access to the index,+-- discarding the results.+--+-- When you don't need access to the index then 'mapMOf_' is more flexible in what it accepts.+--+-- @+-- 'mapMOf_' l ≡ 'Control.Lens.Setter.imapMOf' l '.' 'const'+-- @+--+-- @+-- 'imapMOf_' :: 'Monad' m => 'IndexedGetter' i s a     -> (i -> a -> m r) -> s -> m ()+-- 'imapMOf_' :: 'Monad' m => 'IndexedFold' i s a       -> (i -> a -> m r) -> s -> m ()+-- 'imapMOf_' :: 'Monad' m => 'IndexedLens'' i s a      -> (i -> a -> m r) -> s -> m ()+-- 'imapMOf_' :: 'Monad' m => 'IndexedTraversal'' i s a -> (i -> a -> m r) -> s -> m ()+-- @+imapMOf_ :: Monad m => IndexedGetting i (Sequenced r m) s a -> (i -> a -> m r) -> s -> m ()+imapMOf_ l f = liftM skip . getSequenced #. getConst #. l (Const #. Sequenced #. Indexed f)+{-# INLINE imapMOf_ #-}++-- | Run monadic actions for each target of an 'IndexedFold' or 'IndexedTraversal' with access to the index,+-- discarding the results (with the arguments flipped).+--+-- @+-- 'iforMOf_' ≡ 'flip' '.' 'imapMOf_'+-- @+--+-- When you don't need access to the index then 'forMOf_' is more flexible in what it accepts.+--+-- @+-- 'forMOf_' l a ≡ 'Control.Lens.Traversal.iforMOf' l a '.' 'const'+-- @+--+-- @+-- 'iforMOf_' :: 'Monad' m => 'IndexedGetter' i s a     -> s -> (i -> a -> m r) -> m ()+-- 'iforMOf_' :: 'Monad' m => 'IndexedFold' i s a       -> s -> (i -> a -> m r) -> m ()+-- 'iforMOf_' :: 'Monad' m => 'IndexedLens'' i s a      -> s -> (i -> a -> m r) -> m ()+-- 'iforMOf_' :: 'Monad' m => 'IndexedTraversal'' i s a -> s -> (i -> a -> m r) -> m ()+-- @+iforMOf_ :: Monad m => IndexedGetting i (Sequenced r m) s a -> s -> (i -> a -> m r) -> m ()+iforMOf_ = flip . imapMOf_+{-# INLINE iforMOf_ #-}++-- | Concatenate the results of a function of the elements of an 'IndexedFold' or 'IndexedTraversal'+-- with access to the index.+--+-- When you don't need access to the index then 'concatMapOf'  is more flexible in what it accepts.+--+-- @+-- 'concatMapOf' l ≡ 'iconcatMapOf' l '.' 'const'+-- 'iconcatMapOf' ≡ 'ifoldMapOf'+-- @+--+-- @+-- 'iconcatMapOf' :: 'IndexedGetter' i s a     -> (i -> a -> [r]) -> s -> [r]+-- 'iconcatMapOf' :: 'IndexedFold' i s a       -> (i -> a -> [r]) -> s -> [r]+-- 'iconcatMapOf' :: 'IndexedLens'' i s a      -> (i -> a -> [r]) -> s -> [r]+-- 'iconcatMapOf' :: 'IndexedTraversal'' i s a -> (i -> a -> [r]) -> s -> [r]+-- @+iconcatMapOf :: IndexedGetting i [r] s a -> (i -> a -> [r]) -> s -> [r]+iconcatMapOf = ifoldMapOf+{-# INLINE iconcatMapOf #-}++-- | The 'ifindOf' function takes an 'IndexedFold' or 'IndexedTraversal', a predicate that is also+-- supplied the index, a structure and returns the left-most element of the structure+-- matching the predicate, or 'Nothing' if there is no such element.+--+-- When you don't need access to the index then 'findOf' is more flexible in what it accepts.+--+-- @+-- 'findOf' l ≡ 'ifindOf' l '.' 'const'+-- @+--+-- @+-- 'ifindOf' :: 'IndexedGetter' i s a     -> (i -> a -> 'Bool') -> s -> 'Maybe' a+-- 'ifindOf' :: 'IndexedFold' i s a       -> (i -> a -> 'Bool') -> s -> 'Maybe' a+-- 'ifindOf' :: 'IndexedLens'' i s a      -> (i -> a -> 'Bool') -> s -> 'Maybe' a+-- 'ifindOf' :: 'IndexedTraversal'' i s a -> (i -> a -> 'Bool') -> s -> 'Maybe' a+-- @+ifindOf :: IndexedGetting i (Endo (Maybe a)) s a -> (i -> a -> Bool) -> s -> Maybe a+ifindOf l f = ifoldrOf l (\i a y -> if f i a then Just a else y) Nothing+{-# INLINE ifindOf #-}++-- | The 'ifindMOf' function takes an 'IndexedFold' or 'IndexedTraversal', a monadic predicate that is also+-- supplied the index, a structure and returns in the monad the left-most element of the structure+-- matching the predicate, or 'Nothing' if there is no such element.+--+-- When you don't need access to the index then 'findMOf' is more flexible in what it accepts.+--+-- @+-- 'findMOf' l ≡ 'ifindMOf' l '.' 'const'+-- @+--+-- @+-- 'ifindMOf' :: 'Monad' m => 'IndexedGetter' i s a     -> (i -> a -> m 'Bool') -> s -> m ('Maybe' a)+-- 'ifindMOf' :: 'Monad' m => 'IndexedFold' i s a       -> (i -> a -> m 'Bool') -> s -> m ('Maybe' a)+-- 'ifindMOf' :: 'Monad' m => 'IndexedLens'' i s a      -> (i -> a -> m 'Bool') -> s -> m ('Maybe' a)+-- 'ifindMOf' :: 'Monad' m => 'IndexedTraversal'' i s a -> (i -> a -> m 'Bool') -> s -> m ('Maybe' a)+-- @+ifindMOf :: Monad m => IndexedGetting i (Endo (m (Maybe a))) s a -> (i -> a -> m Bool) -> s -> m (Maybe a)+ifindMOf l f = ifoldrOf l (\i a y -> f i a >>= \r -> if r then return (Just a) else y) $ return Nothing+{-# INLINE ifindMOf #-}++-- | /Strictly/ fold right over the elements of a structure with an index.+--+-- When you don't need access to the index then 'foldrOf'' is more flexible in what it accepts.+--+-- @+-- 'foldrOf'' l ≡ 'ifoldrOf'' l '.' 'const'+-- @+--+-- @+-- 'ifoldrOf'' :: 'IndexedGetter' i s a     -> (i -> a -> r -> r) -> r -> s -> r+-- 'ifoldrOf'' :: 'IndexedFold' i s a       -> (i -> a -> r -> r) -> r -> s -> r+-- 'ifoldrOf'' :: 'IndexedLens'' i s a      -> (i -> a -> r -> r) -> r -> s -> r+-- 'ifoldrOf'' :: 'IndexedTraversal'' i s a -> (i -> a -> r -> r) -> r -> s -> r+-- @+ifoldrOf' :: IndexedGetting i (Dual (Endo (r -> r))) s a -> (i -> a -> r -> r) -> r -> s -> r+ifoldrOf' l f z0 xs = ifoldlOf l f' id xs z0+  where f' i k x z = k $! f i x z+{-# INLINE ifoldrOf' #-}++-- | Fold over the elements of a structure with an index, associating to the left, but /strictly/.+--+-- When you don't need access to the index then 'foldlOf'' is more flexible in what it accepts.+--+-- @+-- 'foldlOf'' l ≡ 'ifoldlOf'' l '.' 'const'+-- @+--+-- @+-- 'ifoldlOf'' :: 'IndexedGetter' i s a       -> (i -> r -> a -> r) -> r -> s -> r+-- 'ifoldlOf'' :: 'IndexedFold' i s a         -> (i -> r -> a -> r) -> r -> s -> r+-- 'ifoldlOf'' :: 'IndexedLens'' i s a        -> (i -> r -> a -> r) -> r -> s -> r+-- 'ifoldlOf'' :: 'IndexedTraversal'' i s a   -> (i -> r -> a -> r) -> r -> s -> r+-- @+ifoldlOf' :: IndexedGetting i (Endo (r -> r)) s a -> (i -> r -> a -> r) -> r -> s -> r+ifoldlOf' l f z0 xs = ifoldrOf l f' id xs z0+  where f' i x k z = k $! f i z x+{-# INLINE ifoldlOf' #-}++-- | Monadic fold right over the elements of a structure with an index.+--+-- When you don't need access to the index then 'foldrMOf' is more flexible in what it accepts.+--+-- @+-- 'foldrMOf' l ≡ 'ifoldrMOf' l '.' 'const'+-- @+--+-- @+-- 'ifoldrMOf' :: 'Monad' m => 'IndexedGetter' i s a     -> (i -> a -> r -> m r) -> r -> s -> m r+-- 'ifoldrMOf' :: 'Monad' m => 'IndexedFold' i s a       -> (i -> a -> r -> m r) -> r -> s -> m r+-- 'ifoldrMOf' :: 'Monad' m => 'IndexedLens'' i s a      -> (i -> a -> r -> m r) -> r -> s -> m r+-- 'ifoldrMOf' :: 'Monad' m => 'IndexedTraversal'' i s a -> (i -> a -> r -> m r) -> r -> s -> m r+-- @+ifoldrMOf :: Monad m => IndexedGetting i (Dual (Endo (r -> m r))) s a -> (i -> a -> r -> m r) -> r -> s -> m r+ifoldrMOf l f z0 xs = ifoldlOf l f' return xs z0+  where f' i k x z = f i x z >>= k+{-# INLINE ifoldrMOf #-}++-- | Monadic fold over the elements of a structure with an index, associating to the left.+--+-- When you don't need access to the index then 'foldlMOf' is more flexible in what it accepts.+--+-- @+-- 'foldlMOf' l ≡ 'ifoldlMOf' l '.' 'const'+-- @+--+-- @+-- 'ifoldlMOf' :: 'Monad' m => 'IndexedGetter' i s a     -> (i -> r -> a -> m r) -> r -> s -> m r+-- 'ifoldlMOf' :: 'Monad' m => 'IndexedFold' i s a       -> (i -> r -> a -> m r) -> r -> s -> m r+-- 'ifoldlMOf' :: 'Monad' m => 'IndexedLens'' i s a      -> (i -> r -> a -> m r) -> r -> s -> m r+-- 'ifoldlMOf' :: 'Monad' m => 'IndexedTraversal'' i s a -> (i -> r -> a -> m r) -> r -> s -> m r+-- @+ifoldlMOf :: Monad m => IndexedGetting i (Endo (r -> m r)) s a -> (i -> r -> a -> m r) -> r -> s -> m r+ifoldlMOf l f z0 xs = ifoldrOf l f' return xs z0+  where f' i x k z = f i z x >>= k+{-# INLINE ifoldlMOf #-}++-- | Extract the key-value pairs from a structure.+--+-- When you don't need access to the indices in the result, then 'toListOf' is more flexible in what it accepts.+--+-- @+-- 'toListOf' l ≡ 'map' 'snd' '.' 'itoListOf' l+-- @+--+-- @+-- 'itoListOf' :: 'IndexedGetter' i s a     -> s -> [(i,a)]+-- 'itoListOf' :: 'IndexedFold' i s a       -> s -> [(i,a)]+-- 'itoListOf' :: 'IndexedLens'' i s a      -> s -> [(i,a)]+-- 'itoListOf' :: 'IndexedTraversal'' i s a -> s -> [(i,a)]+-- @+itoListOf :: IndexedGetting i (Endo [(i,a)]) s a -> s -> [(i,a)]+itoListOf l = ifoldrOf l (\i a -> ((i,a):)) []+{-# INLINE itoListOf #-}++-- | An infix version of 'itoListOf'.++-- @+-- ('^@..') :: s -> 'IndexedGetter' i s a     -> [(i,a)]+-- ('^@..') :: s -> 'IndexedFold' i s a       -> [(i,a)]+-- ('^@..') :: s -> 'IndexedLens'' i s a      -> [(i,a)]+-- ('^@..') :: s -> 'IndexedTraversal'' i s a -> [(i,a)]+-- @+(^@..) :: s -> IndexedGetting i (Endo [(i,a)]) s a -> [(i,a)]+s ^@.. l = ifoldrOf l (\i a -> ((i,a):)) [] s+{-# INLINE (^@..) #-}++-- | Perform a safe 'head' (with index) of an 'IndexedFold' or 'IndexedTraversal' or retrieve 'Just' the index and result+-- from an 'IndexedGetter' or 'IndexedLens'.+--+-- When using a 'IndexedTraversal' as a partial 'IndexedLens', or an 'IndexedFold' as a partial 'IndexedGetter' this can be a convenient+-- way to extract the optional value.+--+-- @+-- ('^@?') :: s -> 'IndexedGetter' i s a     -> 'Maybe' (i, a)+-- ('^@?') :: s -> 'IndexedFold' i s a       -> 'Maybe' (i, a)+-- ('^@?') :: s -> 'IndexedLens'' i s a      -> 'Maybe' (i, a)+-- ('^@?') :: s -> 'IndexedTraversal'' i s a -> 'Maybe' (i, a)+-- @+(^@?) :: s -> IndexedGetting i (Endo (Maybe (i, a))) s a -> Maybe (i, a)+s ^@? l = ifoldrOf l (\i x _ -> Just (i,x)) Nothing s+{-# INLINE (^@?) #-}++-- | Perform an *UNSAFE* 'head' (with index) of an 'IndexedFold' or 'IndexedTraversal' assuming that it is there.+--+-- @+-- ('^@?!') :: s -> 'IndexedGetter' i s a     -> (i, a)+-- ('^@?!') :: s -> 'IndexedFold' i s a       -> (i, a)+-- ('^@?!') :: s -> 'IndexedLens'' i s a      -> (i, a)+-- ('^@?!') :: s -> 'IndexedTraversal'' i s a -> (i, a)+-- @+(^@?!) :: HasCallStack => s -> IndexedGetting i (Endo (i, a)) s a -> (i, a)+s ^@?! l = ifoldrOf l (\i x _ -> (i,x)) (error "(^@?!): empty Fold") s+{-# INLINE (^@?!) #-}++-- | Retrieve the index of the first value targeted by a 'IndexedFold' or 'IndexedTraversal' which is equal to a given value.+--+-- @+-- 'Data.List.elemIndex' ≡ 'elemIndexOf' 'folded'+-- @+--+-- @+-- 'elemIndexOf' :: 'Eq' a => 'IndexedFold' i s a       -> a -> s -> 'Maybe' i+-- 'elemIndexOf' :: 'Eq' a => 'IndexedTraversal'' i s a -> a -> s -> 'Maybe' i+-- @+elemIndexOf :: Eq a => IndexedGetting i (First i) s a -> a -> s -> Maybe i+elemIndexOf l a = findIndexOf l (a ==)+{-# INLINE elemIndexOf #-}++-- | Retrieve the indices of the values targeted by a 'IndexedFold' or 'IndexedTraversal' which are equal to a given value.+--+-- @+-- 'Data.List.elemIndices' ≡ 'elemIndicesOf' 'folded'+-- @+--+-- @+-- 'elemIndicesOf' :: 'Eq' a => 'IndexedFold' i s a       -> a -> s -> [i]+-- 'elemIndicesOf' :: 'Eq' a => 'IndexedTraversal'' i s a -> a -> s -> [i]+-- @+elemIndicesOf :: Eq a => IndexedGetting i (Endo [i]) s a -> a -> s -> [i]+elemIndicesOf l a = findIndicesOf l (a ==)+{-# INLINE elemIndicesOf #-}++-- | Retrieve the index of the first value targeted by a 'IndexedFold' or 'IndexedTraversal' which satisfies a predicate.+--+-- @+-- 'Data.List.findIndex' ≡ 'findIndexOf' 'folded'+-- @+--+-- @+-- 'findIndexOf' :: 'IndexedFold' i s a       -> (a -> 'Bool') -> s -> 'Maybe' i+-- 'findIndexOf' :: 'IndexedTraversal'' i s a -> (a -> 'Bool') -> s -> 'Maybe' i+-- @+findIndexOf :: IndexedGetting i (First i) s a -> (a -> Bool) -> s -> Maybe i+findIndexOf l p = preview (l . filtered p . asIndex)+{-# INLINE findIndexOf #-}++-- | Retrieve the indices of the values targeted by a 'IndexedFold' or 'IndexedTraversal' which satisfy a predicate.+--+-- @+-- 'Data.List.findIndices' ≡ 'findIndicesOf' 'folded'+-- @+--+-- @+-- 'findIndicesOf' :: 'IndexedFold' i s a       -> (a -> 'Bool') -> s -> [i]+-- 'findIndicesOf' :: 'IndexedTraversal'' i s a -> (a -> 'Bool') -> s -> [i]+-- @+findIndicesOf :: IndexedGetting i (Endo [i]) s a -> (a -> Bool) -> s -> [i]+findIndicesOf l p = toListOf (l . filtered p . asIndex)+{-# INLINE findIndicesOf #-}++-------------------------------------------------------------------------------+-- Converting to Folds+-------------------------------------------------------------------------------++-- | Filter an 'IndexedFold' or 'IndexedGetter', obtaining an 'IndexedFold'.+--+-- >>> [0,0,0,5,5,5]^..traversed.ifiltered (\i a -> i <= a)+-- [0,5,5,5]+--+-- Compose with 'ifiltered' to filter another 'IndexedLens', 'IndexedIso', 'IndexedGetter', 'IndexedFold' (or 'IndexedTraversal') with+-- access to both the value and the index.+--+-- Note: As with 'filtered', this is /not/ a legal 'IndexedTraversal', unless you are very careful not to invalidate the predicate on the target!+ifiltered :: (Indexable i p, Applicative f) => (i -> a -> Bool) -> Optical' p (Indexed i) f a a+ifiltered p f = Indexed $ \i a -> if p i a then indexed f i a else pure a+{-# INLINE ifiltered #-}++-- | Obtain an 'IndexedFold' by taking elements from another+-- 'IndexedFold', 'IndexedLens', 'IndexedGetter' or 'IndexedTraversal' while a predicate holds.+--+-- @+-- 'itakingWhile' :: (i -> a -> 'Bool') -> 'IndexedFold' i s a          -> 'IndexedFold' i s a+-- 'itakingWhile' :: (i -> a -> 'Bool') -> 'IndexedTraversal'' i s a    -> 'IndexedFold' i s a+-- 'itakingWhile' :: (i -> a -> 'Bool') -> 'IndexedLens'' i s a         -> 'IndexedFold' i s a+-- 'itakingWhile' :: (i -> a -> 'Bool') -> 'IndexedGetter' i s a        -> 'IndexedFold' i s a+-- @+--+-- Note: Applying 'itakingWhile' to an 'IndexedLens' or 'IndexedTraversal' will still allow you to use it as a+-- pseudo-'IndexedTraversal', but if you change the value of any target to one where the predicate returns+-- 'False', then you will break the 'Traversal' laws and 'Traversal' fusion will no longer be sound.+itakingWhile :: (Indexable i p, Profunctor q, Contravariant f, Applicative f)+         => (i -> a -> Bool)+         -> Optical' (Indexed i) q (Const (Endo (f s))) s a+         -> Optical' p q f s a+itakingWhile p l f = (flip appEndo noEffect .# getConst) `rmap` l g where+  g = Indexed $ \i a -> Const . Endo $ if p i a then (indexed f i a *>) else const noEffect+{-# INLINE itakingWhile #-}++-- | Obtain an 'IndexedFold' by dropping elements from another 'IndexedFold', 'IndexedLens', 'IndexedGetter' or 'IndexedTraversal' while a predicate holds.+--+-- @+-- 'idroppingWhile' :: (i -> a -> 'Bool') -> 'IndexedFold' i s a          -> 'IndexedFold' i s a+-- 'idroppingWhile' :: (i -> a -> 'Bool') -> 'IndexedTraversal'' i s a    -> 'IndexedFold' i s a -- see notes+-- 'idroppingWhile' :: (i -> a -> 'Bool') -> 'IndexedLens'' i s a         -> 'IndexedFold' i s a -- see notes+-- 'idroppingWhile' :: (i -> a -> 'Bool') -> 'IndexedGetter' i s a        -> 'IndexedFold' i s a+-- @+--+-- Note: As with `droppingWhile` applying 'idroppingWhile' to an 'IndexedLens' or 'IndexedTraversal' will still+-- allow you to use it as a pseudo-'IndexedTraversal', but if you change the value of the first target to one+-- where the predicate returns 'True', then you will break the 'Traversal' laws and 'Traversal' fusion will+-- no longer be sound.+idroppingWhile :: (Indexable i p, Profunctor q, Applicative f)+              => (i -> a -> Bool)+              -> Optical (Indexed i) q (Compose (State Bool) f) s t a a+              -> Optical p q f s t a a+idroppingWhile p l f = (flip evalState True .# getCompose) `rmap` l g where+  g = Indexed $ \ i a -> Compose $ state $ \b -> let+      b' = b && p i a+    in (if b' then pure a else indexed f i a, b')+{-# INLINE idroppingWhile #-}++------------------------------------------------------------------------------+-- Misc.+------------------------------------------------------------------------------++skip :: a -> ()+skip _ = ()+{-# INLINE skip #-}++------------------------------------------------------------------------------+-- Folds with Reified Monoid+------------------------------------------------------------------------------++-- | Fold a value using a specified 'Fold' and 'Monoid' operations.+-- This is like 'foldBy' where the 'Foldable' instance can be+-- manually specified.+--+-- @+-- 'foldByOf' 'folded' ≡ 'foldBy'+-- @+--+-- @+-- 'foldByOf' :: 'Getter' s a     -> (a -> a -> a) -> a -> s -> a+-- 'foldByOf' :: 'Fold' s a       -> (a -> a -> a) -> a -> s -> a+-- 'foldByOf' :: 'Lens'' s a      -> (a -> a -> a) -> a -> s -> a+-- 'foldByOf' :: 'Traversal'' s a -> (a -> a -> a) -> a -> s -> a+-- 'foldByOf' :: 'Iso'' s a       -> (a -> a -> a) -> a -> s -> a+-- @+--+-- >>> foldByOf both (++) [] ("hello","world")+-- "helloworld"+foldByOf :: Fold s a -> (a -> a -> a) -> a -> s -> a+foldByOf l f z = reifyMonoid f z (foldMapOf l ReflectedMonoid)++-- | Fold a value using a specified 'Fold' and 'Monoid' operations.+-- This is like 'foldMapBy' where the 'Foldable' instance can be+-- manually specified.+--+-- @+-- 'foldMapByOf' 'folded' ≡ 'foldMapBy'+-- @+--+-- @+-- 'foldMapByOf' :: 'Getter' s a     -> (r -> r -> r) -> r -> (a -> r) -> s -> r+-- 'foldMapByOf' :: 'Fold' s a       -> (r -> r -> r) -> r -> (a -> r) -> s -> r+-- 'foldMapByOf' :: 'Traversal'' s a -> (r -> r -> r) -> r -> (a -> r) -> s -> r+-- 'foldMapByOf' :: 'Lens'' s a      -> (r -> r -> r) -> r -> (a -> r) -> s -> r+-- 'foldMapByOf' :: 'Iso'' s a       -> (r -> r -> r) -> r -> (a -> r) -> s -> r+-- @+--+-- >>> foldMapByOf both (+) 0 length ("hello","world")+-- 10+foldMapByOf :: Fold s a -> (r -> r -> r) -> r -> (a -> r) -> s -> r+foldMapByOf l f z g = reifyMonoid f z (foldMapOf l (ReflectedMonoid #. g))
src/Control/Lens/Getter.hs view
@@ -1,34 +1,38 @@+{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FunctionalDependencies #-}-{-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE Trustworthy #-}++-- Disable the warnings generated by 'Control.Lens.Getter.to', 'ito', 'like', 'ilike'.+-- These functions are intended to produce 'Getters'. Without this constraint+-- users would get warnings when annotating types at uses of these functions.+{-# OPTIONS_GHC -Wno-redundant-constraints #-}+ ------------------------------------------------------------------------------- -- | -- Module      :  Control.Lens.Getter--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional -- Portability :  Rank2Types -- ----- A @'Getter' a c@ is just any function @(a -> c)@, which we've flipped--- into continuation passing style, @(c -> r) -> a -> r@ and decorated--- with 'Accessor' to obtain:+-- A @'Getter' s a@ is just any function @(s -> a)@, which we've flipped+-- into continuation passing style, @(a -> r) -> s -> r@ and decorated+-- with 'Const' to obtain: ----- @type 'Getting' r a b c d = (c -> 'Accessor' r d) -> a -> 'Accessor' r b@+-- @type 'Getting' r s a = (a -> 'Const' r a) -> s -> 'Const' r s@ ----- If we restrict access to knowledge about the type 'r' and can work for--- any d and b, we could get:+-- If we restrict access to knowledge about the type 'r', we could get: ----- @type 'Getter' a c = forall r. 'Getting' r a a c c@+-- @type 'Getter' s a = forall r. 'Getting' r s a@ ----- But we actually hide the use of 'Accessor' behind a class 'Gettable'--- to error messages from type class resolution rather than at unification--- time, where they are much uglier.+-- However, for 'Getter' (but not for 'Getting') we actually permit any+-- functor @f@ which is an instance of both 'Functor' and 'Contravariant': ----- @type 'Getter' a c = forall f. 'Gettable' f => (c -> f c) -> a -> f a@+-- @type 'Getter' s a = forall f. ('Contravariant' f, 'Functor' f) => (a -> f a) -> s -> f s@ -- -- Everything you can do with a function, you can do with a 'Getter', but -- note that because of the continuation passing style ('.') composes them@@ -37,88 +41,82 @@ -- Since it is only a function, every 'Getter' obviously only retrieves a -- single value for a given input. --+-- A common question is whether you can combine multiple 'Getter's to+-- retrieve multiple values. Recall that all 'Getter's are 'Fold's and that+-- we have a @'Monoid' m => 'Applicative' ('Const' m)@ instance to play+-- with. Knowing this, we can use @'Data.Semigroup.<>'@ to glue 'Fold's+-- together:+--+-- >>> (1, 2, 3, 4, 5) ^.. (_2 <> _3 <> _5)+-- [2,3,5]+-- ------------------------------------------------------------------------------- module Control.Lens.Getter   (   -- * Getters-    Getter-  , Getting+    Getter, IndexedGetter+  , Getting, IndexedGetting+  , Accessing   -- * Building Getters   , to+  , ito+  , like+  , ilike   -- * Combinators for Getters and Folds-  , (^.), (^$)-  , (%), (^%)-  , view-  , views-  , use-  , uses-  , query-  , queries--  -- * Storing Getters-  , ReifiedGetter(..)-  , Gettable-  , Accessor+  , (^.)+  , view, views+  , use, uses+  , listening, listenings+  -- * Indexed Getters+  -- ** Indexed Getter Combinators+  , (^@.)+  , iview, iviews+  , iuse, iuses+  , ilistening, ilistenings+  -- * Implementation Details+  , Contravariant(..)+  , getting+  , Const(..)   ) where -import Control.Lens.Internal-import Control.Monad.Reader.Class       as Reader-import Control.Monad.State.Class        as State+import Prelude () +import Control.Lens.Internal.Indexed+import Control.Lens.Internal.Prelude+import Control.Lens.Type+import Control.Monad.Reader.Class as Reader+import Control.Monad.State        as State+import Control.Monad.Writer (MonadWriter (..))+ -- $setup+-- >>> :set -XNoOverloadedStrings -- >>> import Control.Lens--infixl 8 ^., ^%-infixl 1 %-infixr 0 ^$------------------------------------------------------------------------------------ Pipelining------------------------------------------------------------------------------------ | Passes the result of the left side to the function on the right side (forward pipe operator).------ This is the flipped version of ('$'), which is more common in languages like F# as (@|>@) where it is needed--- for inference. Here it is supplied for notational convenience and given a precedence that allows it--- to be nested inside uses of ('$').------ >>> "hello" % length % succ--- 6-(%) :: a -> (a -> b) -> b-a % f = f a-{-# INLINE (%) #-}---- | A version of ('Control.Lens.Combinators.%') with much tighter precedence that can be interleaved with ('^.')------ >>> "hello"^%length--- 5+-- >>> import Control.Monad.State -- >>> import Data.List.Lens--- >>> ("hello","world")^._1^%reverse^._head--- 'o'-(^%) :: a -> (a -> b) -> b-a ^% f = f a+-- >>> import Data.Semigroup (Semigroup (..))+-- >>> import Debug.SimpleReflect.Expr+-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g)+-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f+-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g +infixl 8 ^., ^@.+ ------------------------------------------------------------------------------- -- Getters ------------------------------------------------------------------------------- --- | A 'Getter' describes how to retrieve a single value in a way that can be--- composed with other lens-like constructions.------ Unlike a 'Control.Lens.Type.Lens' a 'Getter' is read-only. Since a 'Getter'--- cannot be used to write back there are no lens laws that can be applied to--- it. In fact, it is isomorphic to an arbitrary function from @(a -> c)@.------ Moreover, a 'Getter' can be used directly as a 'Control.Lens.Fold.Fold',--- since it just ignores the 'Applicative'.-type Getter a c = forall f. Gettable f => (c -> f c) -> a -> f a---- | Build a 'Getter' from an arbitrary Haskell function.+-- | Build an (index-preserving) 'Getter' from an arbitrary Haskell function. ----- @'to' f . 'to' g = 'to' (g . f)@+-- @+-- 'Control.Lens.Getter.to' f '.' 'Control.Lens.Getter.to' g ≡ 'Control.Lens.Getter.to' (g '.' f)+-- @ ----- @a '^.' 'to' f = f a@+-- @+-- a '^.' 'Control.Lens.Getter.to' f ≡ f a+-- @ --+-- >>> a ^.to f+-- f a -- -- >>> ("hello","world")^.to snd -- "world"@@ -128,36 +126,91 @@ -- -- >>> (0, -5)^._2.to abs -- 5-to :: (a -> c) -> Getter a c-to f g = coerce . g . f+--+-- @+-- 'Control.Lens.Getter.to' :: (s -> a) -> 'IndexPreservingGetter' s a+-- @+to :: (Profunctor p, Contravariant f) => (s -> a) -> Optic' p f s a+to k = dimap k (contramap k) {-# INLINE to #-} +-- |+-- @+-- 'ito' :: (s -> (i, a)) -> 'IndexedGetter' i s a+-- @+ito :: (Indexable i p, Contravariant f) => (s -> (i, a)) -> Over' p f s a+ito k = dimap k (contramap (snd . k)) . uncurry . indexed+{-# INLINE ito #-} ++-- | Build an constant-valued (index-preserving) 'Getter' from an arbitrary Haskell value.+--+-- @+-- 'like' a '.' 'like' b ≡ 'like' b+-- a '^.' 'like' b ≡ b+-- a '^.' 'like' b ≡ a '^.' 'Control.Lens.Getter.to' ('const' b)+-- @+--+-- This can be useful as a second case 'failing' a 'Fold'+-- e.g. @foo `failing` 'like' 0@+--+-- @+-- 'like' :: a -> 'IndexPreservingGetter' s a+-- @+like :: (Profunctor p, Contravariant f, Functor f) => a -> Optic' p f s a+like a = to (const a)+{-# INLINE like #-}+ -- |+-- @+-- 'ilike' :: i -> a -> 'IndexedGetter' i s a+-- @+ilike :: (Indexable i p, Contravariant f, Functor f) => i -> a -> Over' p f s a+ilike i a = ito (const (i, a))+{-# INLINE ilike #-}++-- | When you see this in a type signature it indicates that you can+-- pass the function a 'Lens', 'Getter',+-- 'Control.Lens.Traversal.Traversal', 'Control.Lens.Fold.Fold',+-- 'Control.Lens.Prism.Prism', 'Control.Lens.Iso.Iso', or one of+-- the indexed variants, and it will just \"do the right thing\".+-- -- Most 'Getter' combinators are able to be used with both a 'Getter' or a -- 'Control.Lens.Fold.Fold' in limited situations, to do so, they need to be--- monomorphic in what we are going to extract with 'Const'. To be compatible--- with 'Control.Lens.Type.Lens', 'Control.Lens.Traversal.Traversal' and--- 'Control.Lens.Iso.Iso' we also restricted choices of the irrelevant @b@ and--- @d@ parameters.+-- monomorphic in what we are going to extract with 'Control.Applicative.Const'. To be compatible+-- with 'Lens', 'Control.Lens.Traversal.Traversal' and+-- 'Control.Lens.Iso.Iso' we also restricted choices of the irrelevant @t@ and+-- @b@ parameters. ----- If a function accepts a @'Getting' r a b c d@, then when @r@ is a 'Monoid', then+-- If a function accepts a @'Getting' r s a@, then when @r@ is a 'Data.Monoid.Monoid', then -- you can pass a 'Control.Lens.Fold.Fold' (or -- 'Control.Lens.Traversal.Traversal'), otherwise you can only pass this a--- 'Getter' or 'Control.Lens.Type.Lens'.-type Getting r a b c d = (c -> Accessor r d) -> a -> Accessor r b+-- 'Getter' or 'Lens'.+type Getting r s a = (a -> Const r a) -> s -> Const r s +-- | Used to consume an 'Control.Lens.Fold.IndexedFold'.+type IndexedGetting i m s a = Indexed i a (Const m a) -> s -> Const m s++-- | This is a convenient alias used when consuming (indexed) getters and (indexed) folds+-- in a highly general fashion.+type Accessing p m s a = p a (Const m a) -> s -> Const m s+ ------------------------------------------------------------------------------- -- Getting Values -------------------------------------------------------------------------------  -- | View the value pointed to by a 'Getter', 'Control.Lens.Iso.Iso' or--- 'Control.Lens.Type.Lens' or the result of folding over all the results of a+-- 'Lens' or the result of folding over all the results of a -- 'Control.Lens.Fold.Fold' or 'Control.Lens.Traversal.Traversal' that points--- at a monoidal values.+-- at a monoidal value. ----- @'view' . 'to' = 'id'@+-- @+-- 'view' '.' 'Control.Lens.Getter.to' ≡ 'id'+-- @ --+-- >>> view (to f) a+-- f a+-- -- >>> view _2 (1,"hello") -- "hello" --@@ -168,76 +221,84 @@ -- "world" -- ----- It may be useful to think of 'view' as having one of these more restrictive--- signatures:+-- As 'view' is commonly used to access the target of a 'Getter' or obtain a monoidal summary of the targets of a 'Fold',+-- It may be useful to think of it as having one of these more restricted signatures: -- -- @--- 'view' ::             'Getter' a c             -> a -> c--- 'view' :: 'Monoid' m => 'Control.Lens.Fold.Fold' a m               -> a -> m--- 'view' ::             'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a c         -> a -> c--- 'view' ::             'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a c        -> a -> c--- 'view' :: 'Monoid' m => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a m   -> a -> m+-- 'view' ::             'Getter' s a     -> s -> a+-- 'view' :: 'Data.Monoid.Monoid' m => 'Control.Lens.Fold.Fold' s m       -> s -> m+-- 'view' ::             'Control.Lens.Iso.Iso'' s a       -> s -> a+-- 'view' ::             'Lens'' s a      -> s -> a+-- 'view' :: 'Data.Monoid.Monoid' m => 'Control.Lens.Traversal.Traversal'' s m -> s -> m -- @-view :: Getting c a b c d -> a -> c-view l = runAccessor . l Accessor+--+-- In a more general setting, such as when working with a 'Monad' transformer stack you can use:+--+-- @+-- 'view' :: 'MonadReader' s m             => 'Getter' s a     -> m a+-- 'view' :: ('MonadReader' s m, 'Data.Monoid.Monoid' a) => 'Control.Lens.Fold.Fold' s a       -> m a+-- 'view' :: 'MonadReader' s m             => 'Control.Lens.Iso.Iso'' s a       -> m a+-- 'view' :: 'MonadReader' s m             => 'Lens'' s a      -> m a+-- 'view' :: ('MonadReader' s m, 'Data.Monoid.Monoid' a) => 'Control.Lens.Traversal.Traversal'' s a -> m a+-- @+view :: MonadReader s m => Getting a s a -> m a+view l = Reader.asks (getConst #. l Const) {-# INLINE view #-} --- | View the value of a 'Getter', 'Control.Lens.Iso.Iso',--- 'Control.Lens.Type.Lens' or the result of folding over the result of mapping--- the targets of a 'Control.Lens.Fold.Fold' or+-- | View a function of the value pointed to by a 'Getter' or 'Lens' or the result of+-- folding over the result of mapping the targets of a 'Control.Lens.Fold.Fold' or -- 'Control.Lens.Traversal.Traversal'. ----- It may be useful to think of 'views' as having these more restrictive--- signatures:+-- @+-- 'views' l f ≡ 'view' (l '.' 'Control.Lens.Getter.to' f)+-- @ ----- @'views' l f = 'view' (l '.' 'to' f)@+-- >>> views (to f) g a+-- g (f a) -- -- >>> views _2 length (1,"hello") -- 5 --+-- As 'views' is commonly used to access the target of a 'Getter' or obtain a monoidal summary of the targets of a 'Fold',+-- It may be useful to think of it as having one of these more restricted signatures:+-- -- @--- 'views' ::             'Getter' a c             -> (c -> d) -> a -> d--- 'views' :: 'Monoid' m => 'Control.Lens.Fold.Fold' a c               -> (c -> m) -> a -> m--- 'views' ::             'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a c         -> (c -> d) -> a -> d--- 'views' ::             'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a c        -> (c -> d) -> a -> d--- 'views' :: 'Monoid' m => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a c   -> (c -> m) -> a -> m+-- 'views' ::             'Getter' s a     -> (a -> r) -> s -> r+-- 'views' :: 'Data.Monoid.Monoid' m => 'Control.Lens.Fold.Fold' s a       -> (a -> m) -> s -> m+-- 'views' ::             'Control.Lens.Iso.Iso'' s a       -> (a -> r) -> s -> r+-- 'views' ::             'Lens'' s a      -> (a -> r) -> s -> r+-- 'views' :: 'Data.Monoid.Monoid' m => 'Control.Lens.Traversal.Traversal'' s a -> (a -> m) -> s -> m -- @-views :: Getting m a b c d -> (c -> m) -> a -> m-views l f = runAccessor . l (Accessor . f)-{-# INLINE views #-}---- | View the value pointed to by a 'Getter', 'Control.Lens.Iso.Iso' or--- 'Control.Lens.Type.Lens' or the result of folding over all the results of a--- 'Control.Lens.Fold.Fold' or 'Control.Lens.Traversal.Traversal' that points--- at a monoidal values. ----- This is the same operation as 'view', only infix.------ @'to' f '^$' x = f x@+-- In a more general setting, such as when working with a 'Monad' transformer stack you can use: ----- >>> _2 ^$ (1, "hello")--- "hello"+-- @+-- 'views' :: 'MonadReader' s m             => 'Getter' s a     -> (a -> r) -> m r+-- 'views' :: ('MonadReader' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Fold.Fold' s a       -> (a -> r) -> m r+-- 'views' :: 'MonadReader' s m             => 'Control.Lens.Iso.Iso'' s a       -> (a -> r) -> m r+-- 'views' :: 'MonadReader' s m             => 'Lens'' s a      -> (a -> r) -> m r+-- 'views' :: ('MonadReader' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Traversal.Traversal'' s a -> (a -> r) -> m r+-- @ -- -- @--- ('^$') ::             'Getter' a c             -> a -> c--- ('^$') :: 'Monoid' m => 'Control.Lens.Fold.Fold' a m               -> a -> m--- ('^$') ::             'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a c         -> a -> c--- ('^$') ::             'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a c        -> a -> c--- ('^$') :: 'Monoid' m => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a m   -> a -> m+-- 'views' :: 'MonadReader' s m => 'Getting' r s a -> (a -> r) -> m r -- @-(^$) :: Getting c a b c d -> a -> c-l ^$ a = runAccessor (l Accessor a)-{-# INLINE (^$) #-}+views :: MonadReader s m => LensLike' (Const r) s a -> (a -> r) -> m r+views l f = Reader.asks (coerce l f)+{-# INLINE views #-} --- | View the value pointed to by a 'Getter' or 'Control.Lens.Type.Lens' or the+-- | View the value pointed to by a 'Getter' or 'Lens' or the -- result of folding over all the results of a 'Control.Lens.Fold.Fold' or -- 'Control.Lens.Traversal.Traversal' that points at a monoidal values. -- -- This is the same operation as 'view' with the arguments flipped. -- -- The fixity and semantics are such that subsequent field accesses can be--- performed with ('Prelude..')+-- performed with ('Prelude..'). --+-- >>> (a,b)^._2+-- b+-- -- >>> ("hello","world")^._2 -- "world" --@@ -246,91 +307,202 @@ -- 2.23606797749979 -- -- @--- ('^.') ::             a -> 'Getter' a c             -> c--- ('^.') :: 'Monoid' m => a -> 'Control.Lens.Fold.Fold' a m               -> m--- ('^.') ::             a -> 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a c         -> c--- ('^.') ::             a -> 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a c        -> c--- ('^.') :: 'Monoid' m => a -> 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a m   -> m+-- ('^.') ::             s -> 'Getter' s a     -> a+-- ('^.') :: 'Data.Monoid.Monoid' m => s -> 'Control.Lens.Fold.Fold' s m       -> m+-- ('^.') ::             s -> 'Control.Lens.Iso.Iso'' s a       -> a+-- ('^.') ::             s -> 'Lens'' s a      -> a+-- ('^.') :: 'Data.Monoid.Monoid' m => s -> 'Control.Lens.Traversal.Traversal'' s m -> m -- @-(^.) :: a -> Getting c a b c d -> c-a ^. l = runAccessor (l Accessor a)+(^.) :: s -> Getting a s a -> a+s ^. l = getConst (l Const s) {-# INLINE (^.) #-}  ------------------------------------------------------------------------------- -- MonadState ------------------------------------------------------------------------------- --- |--- Use the target of a 'Control.Lens.Type.Lens', 'Control.Lens.Iso.Iso', or+-- | Use the target of a 'Lens', 'Control.Lens.Iso.Iso', or -- 'Getter' in the current state, or use a summary of a -- 'Control.Lens.Fold.Fold' or 'Control.Lens.Traversal.Traversal' that points -- to a monoidal value. --+-- >>> evalState (use _1) (a,b)+-- a+--+-- >>> evalState (use _1) ("hello","world")+-- "hello"+-- -- @--- 'use' :: 'MonadState' a m             => 'Getter' a c             -> m c--- 'use' :: ('MonadState' a m, 'Monoid' r) => 'Control.Lens.Fold.Fold' a r               -> m r--- 'use' :: 'MonadState' a m             => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a c         -> m c--- 'use' :: 'MonadState' a m             => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a c        -> m c--- 'use' :: ('MonadState' a m, 'Monoid' r) => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a r   -> m r+-- 'use' :: 'MonadState' s m             => 'Getter' s a     -> m a+-- 'use' :: ('MonadState' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Fold.Fold' s r       -> m r+-- 'use' :: 'MonadState' s m             => 'Control.Lens.Iso.Iso'' s a       -> m a+-- 'use' :: 'MonadState' s m             => 'Lens'' s a      -> m a+-- 'use' :: ('MonadState' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Traversal.Traversal'' s r -> m r -- @-use :: MonadState a m => Getting c a b c d -> m c+use :: MonadState s m => Getting a s a -> m a use l = State.gets (view l) {-# INLINE use #-} --- |--- Use the target of a 'Control.Lens.Type.Lens', 'Control.Lens.Iso.Iso' or+-- | Use the target of a 'Lens', 'Control.Lens.Iso.Iso' or -- 'Getter' in the current state, or use a summary of a -- 'Control.Lens.Fold.Fold' or 'Control.Lens.Traversal.Traversal' that -- points to a monoidal value. --+-- >>> evalState (uses _1 length) ("hello","world")+-- 5+-- -- @--- 'uses' :: 'MonadState' a m             => 'Getter' a c           -> (c -> e) -> m e--- 'uses' :: ('MonadState' a m, 'Monoid' r) => 'Control.Lens.Fold.Fold' a c             -> (c -> r) -> m r--- 'uses' :: 'MonadState' a m             => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a c      -> (c -> e) -> m e--- 'uses' :: 'MonadState' a m             => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> e) -> m e--- 'uses' :: ('MonadState' a m, 'Monoid' r) => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> r) -> m r+-- 'uses' :: 'MonadState' s m             => 'Getter' s a     -> (a -> r) -> m r+-- 'uses' :: ('MonadState' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Fold.Fold' s a       -> (a -> r) -> m r+-- 'uses' :: 'MonadState' s m             => 'Lens'' s a      -> (a -> r) -> m r+-- 'uses' :: 'MonadState' s m             => 'Control.Lens.Iso.Iso'' s a       -> (a -> r) -> m r+-- 'uses' :: ('MonadState' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Traversal.Traversal'' s a -> (a -> r) -> m r -- @-uses :: MonadState a m => Getting e a b c d -> (c -> e) -> m e+--+-- @+-- 'uses' :: 'MonadState' s m => 'Getting' r s t a b -> (a -> r) -> m r+-- @+uses :: MonadState s m => LensLike' (Const r) s a -> (a -> r) -> m r uses l f = State.gets (views l f) {-# INLINE uses #-} ----------------------------------------------------------------------------------- MonadReader--------------------------------------------------------------------------------+-- | This is a generalized form of 'listen' that only extracts the portion of+-- the log that is focused on by a 'Getter'. If given a 'Fold' or a 'Traversal'+-- then a monoidal summary of the parts of the log that are visited will be+-- returned.+--+-- @+-- 'listening' :: 'MonadWriter' w m             => 'Getter' w u     -> m a -> m (a, u)+-- 'listening' :: 'MonadWriter' w m             => 'Lens'' w u      -> m a -> m (a, u)+-- 'listening' :: 'MonadWriter' w m             => 'Iso'' w u       -> m a -> m (a, u)+-- 'listening' :: ('MonadWriter' w m, 'Monoid' u) => 'Fold' w u       -> m a -> m (a, u)+-- 'listening' :: ('MonadWriter' w m, 'Monoid' u) => 'Traversal'' w u -> m a -> m (a, u)+-- 'listening' :: ('MonadWriter' w m, 'Monoid' u) => 'Prism'' w u     -> m a -> m (a, u)+-- @+listening :: MonadWriter w m => Getting u w u -> m a -> m (a, u)+listening l m = do+  (a, w) <- listen m+  return (a, view l w)+{-# INLINE listening #-} --- |--- Query the target of a 'Control.Lens.Type.Lens', 'Control.Lens.Iso.Iso' or--- 'Getter' in the current state, or use a summary of a--- 'Control.Lens.Fold.Fold' or 'Control.Lens.Traversal.Traversal' that points--- to a monoidal value.+-- | This is a generalized form of 'listen' that only extracts the portion of+-- the log that is focused on by a 'Getter'. If given a 'Fold' or a 'Traversal'+-- then a monoidal summary of the parts of the log that are visited will be+-- returned. -- -- @--- 'query' :: 'MonadReader' a m             => 'Getter' a c           -> m c--- 'query' :: ('MonadReader' a m, 'Monoid' c) => 'Control.Lens.Fold.Fold' a c             -> m c--- 'query' :: 'MonadReader' a m             => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a c       -> m c--- 'query' :: 'MonadReader' a m             => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a c      -> m c--- 'query' :: ('MonadReader' a m, 'Monoid' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a c -> m c+-- 'ilistening' :: 'MonadWriter' w m             => 'IndexedGetter' i w u     -> m a -> m (a, (i, u))+-- 'ilistening' :: 'MonadWriter' w m             => 'IndexedLens'' i w u      -> m a -> m (a, (i, u))+-- 'ilistening' :: ('MonadWriter' w m, 'Monoid' u) => 'IndexedFold' i w u       -> m a -> m (a, (i, u))+-- 'ilistening' :: ('MonadWriter' w m, 'Monoid' u) => 'IndexedTraversal'' i w u -> m a -> m (a, (i, u)) -- @-query :: MonadReader a m => Getting c a b c d -> m c-query l = Reader.asks (^.l)-{-# INLINE query #-}+ilistening :: MonadWriter w m => IndexedGetting i (i, u) w u -> m a -> m (a, (i, u))+ilistening l m = do+  (a, w) <- listen m+  return (a, iview l w)+{-# INLINE ilistening #-} --- |--- Use the target of a 'Control.Lens.Type.Lens', 'Control.Lens.Iso.Iso' or--- 'Getter' in the current state, or use a summary of a--- 'Control.Lens.Fold.Fold' or 'Control.Lens.Traversal.Traversal' that points--- to a monoidal value.+-- | This is a generalized form of 'listen' that only extracts the portion of+-- the log that is focused on by a 'Getter'. If given a 'Fold' or a 'Traversal'+-- then a monoidal summary of the parts of the log that are visited will be+-- returned. -- -- @--- 'queries' :: 'MonadReader' a m             => 'Getter' a c           -> (c -> e) -> m e--- 'queries' :: ('MonadReader' a m, 'Monoid' c) => 'Control.Lens.Fold.Fold' a c             -> (c -> e) -> m e--- 'queries' :: 'MonadReader' a m             => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a c       -> (c -> e) -> m e--- 'queries' :: 'MonadReader' a m             => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a c      -> (c -> e) -> m e--- 'queries' :: ('MonadReader' a m, 'Monoid' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a c -> (c -> e) -> m e+-- 'listenings' :: 'MonadWriter' w m             => 'Getter' w u     -> (u -> v) -> m a -> m (a, v)+-- 'listenings' :: 'MonadWriter' w m             => 'Lens'' w u      -> (u -> v) -> m a -> m (a, v)+-- 'listenings' :: 'MonadWriter' w m             => 'Iso'' w u       -> (u -> v) -> m a -> m (a, v)+-- 'listenings' :: ('MonadWriter' w m, 'Monoid' v) => 'Fold' w u       -> (u -> v) -> m a -> m (a, v)+-- 'listenings' :: ('MonadWriter' w m, 'Monoid' v) => 'Traversal'' w u -> (u -> v) -> m a -> m (a, v)+-- 'listenings' :: ('MonadWriter' w m, 'Monoid' v) => 'Prism'' w u     -> (u -> v) -> m a -> m (a, v) -- @-queries :: MonadReader a m => Getting e a b c d -> (c -> e) -> m e-queries l f = Reader.asks (views l f)-{-# INLINE queries #-}+listenings :: MonadWriter w m => Getting v w u -> (u -> v) -> m a -> m (a, v)+listenings l uv m = do+  (a, w) <- listen m+  return (a, views l uv w)+{-# INLINE listenings #-} --- | Useful for storing getters in containers.-newtype ReifiedGetter a c = ReifyGetter { reflectGetter :: Getter a c }+-- | This is a generalized form of 'listen' that only extracts the portion of+-- the log that is focused on by a 'Getter'. If given a 'Fold' or a 'Traversal'+-- then a monoidal summary of the parts of the log that are visited will be+-- returned.+--+-- @+-- 'ilistenings' :: 'MonadWriter' w m             => 'IndexedGetter' w u     -> (i -> u -> v) -> m a -> m (a, v)+-- 'ilistenings' :: 'MonadWriter' w m             => 'IndexedLens'' w u      -> (i -> u -> v) -> m a -> m (a, v)+-- 'ilistenings' :: ('MonadWriter' w m, 'Monoid' v) => 'IndexedFold' w u       -> (i -> u -> v) -> m a -> m (a, v)+-- 'ilistenings' :: ('MonadWriter' w m, 'Monoid' v) => 'IndexedTraversal'' w u -> (i -> u -> v) -> m a -> m (a, v)+-- @+ilistenings :: MonadWriter w m => IndexedGetting i v w u -> (i -> u -> v) -> m a -> m (a, v)+ilistenings l iuv m = do+  (a, w) <- listen m+  return (a, iviews l iuv w)+{-# INLINE ilistenings #-}++------------------------------------------------------------------------------+-- Indexed Getters+------------------------------------------------------------------------------++-- | View the index and value of an 'IndexedGetter' into the current environment as a pair.+--+-- When applied to an 'IndexedFold' the result will most likely be a nonsensical monoidal summary of+-- the indices tupled with a monoidal summary of the values and probably not whatever it is you wanted.+iview :: MonadReader s m => IndexedGetting i (i,a) s a -> m (i,a)+iview l = asks (getConst #. l (Indexed $ \i -> Const #. (,) i))+{-# INLINE iview #-}++-- | View a function of the index and value of an 'IndexedGetter' into the current environment.+--+-- When applied to an 'IndexedFold' the result will be a monoidal summary instead of a single answer.+--+-- @+-- 'iviews' ≡ 'Control.Lens.Fold.ifoldMapOf'+-- @+iviews :: MonadReader s m => IndexedGetting i r s a -> (i -> a -> r) -> m r+iviews l f = asks (coerce l f)+{-# INLINE iviews #-}++-- | Use the index and value of an 'IndexedGetter' into the current state as a pair.+--+-- When applied to an 'IndexedFold' the result will most likely be a nonsensical monoidal summary of+-- the indices tupled with a monoidal summary of the values and probably not whatever it is you wanted.+iuse :: MonadState s m => IndexedGetting i (i,a) s a -> m (i,a)+iuse l = gets (getConst #. l (Indexed $ \i -> Const #. (,) i))+{-# INLINE iuse #-}++-- | Use a function of the index and value of an 'IndexedGetter' into the current state.+--+-- When applied to an 'IndexedFold' the result will be a monoidal summary instead of a single answer.+iuses :: MonadState s m => IndexedGetting i r s a -> (i -> a -> r) -> m r+iuses l f = gets (coerce l f)+{-# INLINE iuses #-}++-- | View the index and value of an 'IndexedGetter' or 'IndexedLens'.+--+-- This is the same operation as 'iview' with the arguments flipped.+--+-- The fixity and semantics are such that subsequent field accesses can be+-- performed with ('Prelude..').+--+-- @+-- ('^@.') :: s -> 'IndexedGetter' i s a -> (i, a)+-- ('^@.') :: s -> 'IndexedLens'' i s a  -> (i, a)+-- @+--+-- The result probably doesn't have much meaning when applied to an 'IndexedFold'.+(^@.) :: s -> IndexedGetting i (i, a) s a -> (i, a)+s ^@. l = getConst $ l (Indexed $ \i -> Const #. (,) i) s+{-# INLINE (^@.) #-}++-- | Coerce a 'Getter'-compatible 'Optical' to an 'Optical''. This+-- is useful when using a 'Traversal' that is not simple as a 'Getter' or a+-- 'Fold'.+--+-- @+-- 'getting' :: 'Traversal' s t a b          -> 'Fold' s a+-- 'getting' :: 'Lens' s t a b               -> 'Getter' s a+-- 'getting' :: 'IndexedTraversal' i s t a b -> 'IndexedFold' i s a+-- 'getting' :: 'IndexedLens' i s t a b      -> 'IndexedGetter' i s a+-- @+getting :: (Profunctor p, Profunctor q, Functor f, Contravariant f)+        => Optical p q f s t a b -> Optical' p q f s a+getting l f = rmap phantom . l $ rmap phantom f
src/Control/Lens/Indexed.hs view
@@ -1,101 +1,292 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-}------------------------------------------------------------------------------++#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-} -- vector, hashable+#endif++#include "lens-common.h"++------------------------------------------------------------------------------- -- | -- Module      :  Control.Lens.Indexed--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional--- Portability :  rank 2 types, MPTCs, TFs, flexible+-- Portability :  Rank2Types ----- Combinators for working with 'Indexed' functions.-----------------------------------------------------------------------------+-- (The classes in here need to be defined together for @DefaultSignatures@ to work.)+------------------------------------------------------------------------------- module Control.Lens.Indexed   (-  -- * Indexed Functions-    Indexed(..)-  , Indexable-  , Index(..)-  , (<.>), (<.), (.>)+  -- * Indexing+    Indexable(..)+  , Conjoined(..)+  , Indexed(..)+  , (<.), (<.>), (.>)+  , selfIndex+  , reindexed   , icompose-  , reindex-  , indexed+  , indexing+  , indexing64+  -- * Indexed Functors+  , FunctorWithIndex(..)+  -- ** Indexed Functor Combinators+  , imapped+  -- * Indexed Foldables+  , FoldableWithIndex(..)+  -- ** Indexed Foldable Combinators+  , ifolded+  , iany+  , iall+  , inone, none+  , itraverse_+  , ifor_+  , imapM_+  , iforM_+  , iconcatMap+  , ifind+  , ifoldrM+  , ifoldlM+  , itoList+  -- * Converting to Folds+  , withIndex+  , asIndex+  -- * Restricting by Index+  , indices+  , index+  -- * Indexed Traversables+  , TraversableWithIndex(..)+  -- * Indexed Traversable Combinators+  , itraversed+  , ifor+  , imapM+  , iforM+  , imapAccumR+  , imapAccumL+  -- * Indexed Folds with Reified Monoid+  , ifoldMapBy+  , ifoldMapByOf+  -- * Indexed Traversals with Reified Applicative+  , itraverseBy+  , itraverseByOf   ) where -import Control.Lens.Internal--infixr 9 <.>, <., .>+import Prelude () --- | Permit overloading of function application for things that also admit a notion of a key or index.+import Data.Functor.WithIndex+import Data.Foldable.WithIndex+import Data.Traversable.WithIndex --- | Provides overloading for 'Indexed' functions.-class Indexed i k where-  -- | Build a function from an 'Indexed' function-  index :: ((i -> a) -> b) -> k a b+import Control.Lens.Fold+import Control.Lens.Getter+import Control.Lens.Internal.Fold+import Control.Lens.Internal.Indexed+import Control.Lens.Internal.Prelude+import Control.Lens.Setter+import Control.Lens.Traversal+import Control.Lens.Type+import Data.Reflection --- | Type alias for passing around polymorphic 'Indexed' functions that can be called 'withIndex' or--- directly as a function-type Indexable i a b = forall k. Indexed i k => k a b+import Data.HashMap.Lazy (HashMap)+import Data.IntMap (IntMap)+import Data.Map (Map)+import Data.Sequence (Seq)+import Data.Vector (Vector) -instance Indexed i (->) where-  index f = f . const-  {-# INLINE index #-}+import qualified Data.HashMap.Lazy as HashMap+import qualified Data.IntMap as IntMap+import qualified Data.Map as Map+import qualified Data.Sequence as Seq+import qualified Data.Vector as Vector --- | A function with access to a index. This constructor may be useful when you need to store--- a 'Indexable' in a container to avoid @ImpredicativeTypes@.-newtype Index i a b = Index { withIndex :: (i -> a) -> b }+infixr 9 <.>, <., .> --- | Using an equality witness to avoid potential overlapping instances--- and aid dispatch.-instance i ~ j => Indexed i (Index j) where-  index = Index-  {-# INLINE index #-}+-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import qualified Data.Map as Map  -- | Compose an 'Indexed' function with a non-indexed function. ----- Mnemonically, the @<@ points to the index we want to preserve.-(<.)  :: Indexed i k => Index i b c -> (a -> b) -> k a c-Index ibc <. ab = index $ \ia -> ibc (ab . ia)+-- Mnemonically, the @<@ points to the indexing we want to preserve.+--+-- >>> let nestedMap = (fmap Map.fromList . Map.fromList) [(1, [(10, "one,ten"), (20, "one,twenty")]), (2, [(30, "two,thirty"), (40,"two,forty")])]+-- >>> nestedMap^..(itraversed<.itraversed).withIndex+-- [(1,"one,ten"),(1,"one,twenty"),(2,"two,thirty"),(2,"two,forty")]+(<.) :: Indexable i p => (Indexed i s t -> r) -> ((a -> b) -> s -> t) -> p a b -> r+(<.) f g h = f . Indexed $ g . indexed h {-# INLINE (<.) #-}  -- | Compose a non-indexed function with an 'Indexed' function. ----- Mnemonically, the @>@ points to the index we want to preserve.-(.>)  :: Indexed i k => (b -> c) -> Index i a b -> k a c-bc .> Index iab = index (bc . iab)+-- Mnemonically, the @>@ points to the indexing we want to preserve.+--+-- This is the same as @('.')@.+--+-- @f '.' g@ (and @f '.>' g@) gives you the index of @g@ unless @g@ is index-preserving, like a+-- 'Prism', 'Iso' or 'Equality', in which case it'll pass through the index of @f@.+--+-- >>> let nestedMap = (fmap Map.fromList . Map.fromList) [(1, [(10, "one,ten"), (20, "one,twenty")]), (2, [(30, "two,thirty"), (40,"two,forty")])]+-- >>> nestedMap^..(itraversed.>itraversed).withIndex+-- [(10,"one,ten"),(20,"one,twenty"),(30,"two,thirty"),(40,"two,forty")]+(.>) :: (st -> r) -> (kab -> st) -> kab -> r+(.>) = (.) {-# INLINE (.>) #-} +-- | Use a value itself as its own index. This is essentially an indexed version of 'id'.+--+-- Note: When used to modify the value, this can break the index requirements assumed by 'indices' and similar,+-- so this is only properly an 'IndexedGetter', but it can be used as more.+--+-- @+-- 'selfIndex' :: 'IndexedGetter' a a b+-- @+selfIndex :: Indexable a p => p a fb -> a -> fb+selfIndex f a = indexed f a a+{-# INLINE selfIndex #-}+ -- | Remap the index.-reindex :: Indexed j k => (i -> j) -> Index i a b -> k a b-reindex ij (Index iab) = index $ \ ja -> iab $ \i -> ja (ij i)-{-# INLINE reindex #-}+reindexed :: Indexable j p => (i -> j) -> (Indexed i a b -> r) -> p a b -> r+reindexed ij f g = f . Indexed $ indexed g . ij+{-# INLINE reindexed #-} --- | Composition of 'Indexed' functions+-- | Composition of 'Indexed' functions. ----- Mnemonically, the @<@ and @>@ points to the fact that we want to preserve the indices.-(<.>) :: Indexed (i, j) k => Index i b c -> Index j a b -> k a c+-- Mnemonically, the @\<@ and @\>@ points to the fact that we want to preserve the indices.+--+-- >>> let nestedMap = (fmap Map.fromList . Map.fromList) [(1, [(10, "one,ten"), (20, "one,twenty")]), (2, [(30, "two,thirty"), (40,"two,forty")])]+-- >>> nestedMap^..(itraversed<.>itraversed).withIndex+-- [((1,10),"one,ten"),((1,20),"one,twenty"),((2,30),"two,thirty"),((2,40),"two,forty")]+(<.>) :: Indexable (i, j) p => (Indexed i s t -> r) -> (Indexed j a b -> s -> t) -> p a b -> r f <.> g = icompose (,) f g {-# INLINE (<.>) #-} --- | Composition of 'Indexed' functions with a user supplied function for combining indexs-icompose :: Indexed k r => (i -> j -> k) -> Index i b c -> Index j a b -> r a c-icompose ijk (Index ibc) (Index jab) = index $ \ka -> ibc $ \i -> jab $ \j -> ka (ijk i j)+-- | Composition of 'Indexed' functions with a user supplied function for combining indices.+icompose :: Indexable p c => (i -> j -> p) -> (Indexed i s t -> r) -> (Indexed j a b -> s -> t) -> c a b -> r+icompose ijk istr jabst cab = istr . Indexed $ \i -> jabst . Indexed $ \j -> indexed cab $ ijk i j {-# INLINE icompose #-} --- | Transform an Traversal into an IndexedTraversal, a Fold into an IndexedFold, etc.+-------------------------------------------------------------------------------+-- Restricting by index+-------------------------------------------------------------------------------++-- | This allows you to filter an 'IndexedFold', 'IndexedGetter', 'IndexedTraversal' or 'IndexedLens' based on a predicate+-- on the indices. ----- @--- 'indexed' :: 'Control.Lens.Traversal.Traversal' a b c d -> 'Control.Lens.IndexedTraversal.IndexedTraversal' 'Int' a b c d--- 'indexed' :: 'Control.Lens.Type.Lens' a b c d      -> 'Control.Lens.IndexedLens.IndexedLens' 'Int' a b c d--- 'indexed' :: 'Control.Lens.Fold.Fold' a b          -> 'Control.Lens.IndexedFold.IndexedFold' 'Int' a b--- 'indexed' :: 'Control.Lens.Iso.Iso' a b c d       -> 'Control.Lens.IndexedLens.IndexedLens' 'Int' a b c d--- 'indexed' :: 'Control.Lens.Getter.Getter' a b        -> 'Control.Lens.IndexedGetter.IndexedGetter' 'Int' a b c d--- @-indexed :: Indexed Int k => ((c -> Indexing f d) -> a -> Indexing f b) -> k (c -> f d) (a -> f b)-indexed l = index $ \icfd a -> case runIndexing (l (\c -> Indexing (\i -> IndexingResult (icfd i c) (i + 1))) a) 0 of-  IndexingResult r _ -> r-{-# INLINE indexed #-}+-- >>> ["hello","the","world","!!!"]^..traversed.indices even+-- ["hello","world"]+--+-- >>> over (traversed.indices (>0)) Prelude.reverse $ ["He","was","stressed","o_O"]+-- ["He","saw","desserts","O_o"]+indices :: (Indexable i p, Applicative f) => (i -> Bool) -> Optical' p (Indexed i) f a a+indices p f = Indexed $ \i a -> if p i then indexed f i a else pure a+{-# INLINE indices #-}++-- | This allows you to filter an 'IndexedFold', 'IndexedGetter', 'IndexedTraversal' or 'IndexedLens' based on an index.+--+-- >>> ["hello","the","world","!!!"]^?traversed.index 2+-- Just "world"+index :: (Indexable i p, Eq i, Applicative f) => i -> Optical' p (Indexed i) f a a+index j f = Indexed $ \i a -> if j == i then indexed f i a else pure a+{-# INLINE index #-}+++-------------------------------------------------------------------------------+-- FunctorWithIndex+-------------------------------------------------------------------------------++-- | The 'IndexedSetter' for a 'FunctorWithIndex'.+--+-- If you don't need access to the index, then 'mapped' is more flexible in what it accepts.+imapped :: FunctorWithIndex i f => IndexedSetter i (f a) (f b) a b+imapped = conjoined mapped (isets imap)+{-# INLINE imapped #-}++-------------------------------------------------------------------------------+-- FoldableWithIndex+-------------------------------------------------------------------------------++-- | The 'IndexedFold' of a 'FoldableWithIndex' container.+--+-- @'ifolded' '.' 'asIndex'@ is a fold over the keys of a 'FoldableWithIndex'.+--+-- >>> Data.Map.fromList [(2, "hello"), (1, "world")]^..ifolded.asIndex+-- [1,2]+ifolded :: FoldableWithIndex i f => IndexedFold i (f a) a+ifolded = conjoined folded $ \f -> phantom . getFolding . ifoldMap (\i -> Folding #. indexed f i)+{-# INLINE ifolded #-}++-------------------------------------------------------------------------------+-- TraversableWithIndex+-------------------------------------------------------------------------------++-- | The 'IndexedTraversal' of a 'TraversableWithIndex' container.+itraversed :: TraversableWithIndex i t => IndexedTraversal i (t a) (t b) a b+itraversed = conjoined traverse (itraverse . indexed)+{-# INLINE [0] itraversed #-}++-------------------------------------------------------------------------------+-- Instances+-------------------------------------------------------------------------------++{-# RULES+"itraversed -> mapList"    itraversed = sets fmap        :: ASetter [a] [b] a b;+"itraversed -> imapList"   itraversed = isets imap       :: AnIndexedSetter Int [a] [b] a b;+"itraversed -> foldrList"  itraversed = foldring foldr   :: Getting (Endo r) [a] a;+"itraversed -> ifoldrList" itraversed = ifoldring ifoldr :: IndexedGetting Int (Endo r) [a] a;+ #-}++{-# RULES+"itraversed -> mapIntMap"    itraversed = sets IntMap.map               :: ASetter (IntMap a) (IntMap b) a b;+"itraversed -> imapIntMap"   itraversed = isets IntMap.mapWithKey       :: AnIndexedSetter Int (IntMap a) (IntMap b) a b;+"itraversed -> foldrIntMap"  itraversed = foldring IntMap.foldr         :: Getting (Endo r) (IntMap a) a;+"itraversed -> ifoldrIntMap" itraversed = ifoldring IntMap.foldrWithKey :: IndexedGetting Int (Endo r) (IntMap a) a;+ #-}++{-# RULES+"itraversed -> mapMap"    itraversed = sets Map.map               :: ASetter (Map k a) (Map k b) a b;+"itraversed -> imapMap"   itraversed = isets Map.mapWithKey       :: AnIndexedSetter k (Map k a) (Map k b) a b;+"itraversed -> foldrMap"  itraversed = foldring Map.foldr         :: Getting (Endo r) (Map k a) a;+"itraversed -> ifoldrMap" itraversed = ifoldring Map.foldrWithKey :: IndexedGetting k (Endo r) (Map k a) a;+ #-}++{-# RULES+"itraversed -> mapHashMap"    itraversed = sets HashMap.map               :: ASetter (HashMap k a) (HashMap k b) a b;+"itraversed -> imapHashMap"   itraversed = isets HashMap.mapWithKey       :: AnIndexedSetter k (HashMap k a) (HashMap k b) a b;+"itraversed -> foldrHashMap"  itraversed = foldring HashMap.foldr         :: Getting (Endo r) (HashMap k a) a;+"itraversed -> ifoldrHashMap" itraversed = ifoldring HashMap.foldrWithKey :: IndexedGetting k (Endo r) (HashMap k a) a;+ #-}++{-# RULES+"itraversed -> mapSeq"    itraversed = sets fmap                    :: ASetter (Seq a) (Seq b) a b;+"itraversed -> imapSeq"   itraversed = isets Seq.mapWithIndex       :: AnIndexedSetter Int (Seq a) (Seq b) a b;+"itraversed -> foldrSeq"  itraversed = foldring foldr               :: Getting (Endo r) (Seq a) a;+"itraversed -> ifoldrSeq" itraversed = ifoldring Seq.foldrWithIndex :: IndexedGetting Int (Endo r) (Seq a) a;+ #-}++{-# RULES+"itraversed -> mapVector"    itraversed = sets Vector.map         :: ASetter (Vector a) (Vector b) a b;+"itraversed -> imapVector"   itraversed = isets Vector.imap       :: AnIndexedSetter Int (Vector a) (Vector b) a b;+"itraversed -> foldrVector"  itraversed = foldring Vector.foldr   :: Getting (Endo r) (Vector a) a;+"itraversed -> ifoldrVector" itraversed = ifoldring Vector.ifoldr :: IndexedGetting Int (Endo r) (Vector a) a;+ #-}++-------------------------------------------------------------------------------+-- Indexed Folds with Reified Monoid+-------------------------------------------------------------------------------++ifoldMapBy :: FoldableWithIndex i t => (r -> r -> r) -> r -> (i -> a -> r) -> t a -> r+ifoldMapBy f z g = reifyMonoid f z (ifoldMap (\i a -> ReflectedMonoid (g i a)))++ifoldMapByOf :: IndexedFold i t a -> (r -> r -> r) -> r -> (i -> a -> r) -> t -> r+ifoldMapByOf l f z g = reifyMonoid f z (ifoldMapOf l (\i a -> ReflectedMonoid (g i a)))++itraverseBy :: TraversableWithIndex i t => (forall x. x -> f x) -> (forall x y. f (x -> y) -> f x -> f y) -> (i -> a -> f b) -> t a -> f (t b)+itraverseBy pur app f = reifyApplicative pur app (itraverse (\i a -> ReflectedApplicative (f i a)))++itraverseByOf :: IndexedTraversal i s t a b -> (forall x. x -> f x) -> (forall x y. f (x -> y) -> f x -> f y) -> (i -> a -> f b) -> s -> f t+itraverseByOf l pur app f = reifyApplicative pur app (itraverseOf l (\i a -> ReflectedApplicative (f i a)))
− src/Control/Lens/IndexedFold.hs
@@ -1,431 +0,0 @@-{-# LANGUAGE Rank2Types #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE FlexibleContexts #-}--------------------------------------------------------------------------------- |--- Module      :  Control.Lens.IndexedFold--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  rank 2 types, MPTCs, TFs, flexible---------------------------------------------------------------------------------module Control.Lens.IndexedFold-  (-  -- * Indexed Folds-    IndexedFold--  -- * Consuming Indexed Folds-  , ifoldMapOf-  , ifoldrOf-  , ifoldlOf-  , ianyOf-  , iallOf-  , itraverseOf_-  , iforOf_-  , imapMOf_-  , iforMOf_-  , iconcatMapOf-  , ifindOf-  , ifoldrOf'-  , ifoldlOf'-  , ifoldrMOf-  , ifoldlMOf-  , itoListOf--  -- * Converting to Folds-  , withIndicesOf-  , indicesOf--  -- * Building Indexed Folds-  , ifiltered-  , itakingWhile-  , idroppingWhile--  -- * Storing Indexed Folds-  , ReifiedIndexedFold(..)-  ) where--import Control.Applicative-import Control.Lens.Indexed-import Control.Lens.IndexedGetter-import Control.Lens.Internal-import Control.Lens.Type-import Control.Monad-import Data.Monoid----------------------------------------------------------------------------------- Indexed Folds----------------------------------------------------------------------------------- | Every 'IndexedFold' is a valid 'Control.Lens.Fold.Fold'.-type IndexedFold i a c = forall k f. (Indexed i k, Applicative f, Gettable f) => k (c -> f c) (a -> f a)---- |--- Fold an 'IndexedFold' or 'Control.Lens.IndexedTraversal.IndexedTraversal' by mapping indices and values to an arbitrary 'Monoid' with access--- to the index @i@.------ When you don't need access to the index then 'Control.Lens.Fold.foldMapOf' is more flexible in what it accepts.------ @'Control.Lens.Fold.foldMapOf' l ≡ 'ifoldMapOf' l '.' 'const'@------ @--- 'ifoldMapOf' ::             'IndexedGetter' i a c          -> (i -> c -> m) -> a -> m--- 'ifoldMapOf' :: 'Monoid' m => 'IndexedFold' i a c            -> (i -> c -> m) -> a -> m--- 'ifoldMapOf' ::             'Control.Lens.IndexedLens.SimpleIndexedLens' i a c      -> (i -> c -> m) -> a -> m--- 'ifoldMapOf' :: 'Monoid' m => 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c -> (i -> c -> m) -> a -> m--- @-ifoldMapOf :: IndexedGetting i m a b c d -> (i -> c -> m) -> a -> m-ifoldMapOf l f = runAccessor . withIndex l (\i -> Accessor . f i)-{-# INLINE ifoldMapOf #-}---- |--- Right-associative fold of parts of a structure that are viewed through an 'IndexedFold' or 'Control.Lens.IndexedTraversal.IndexedTraversal' with--- access to the index @i@.------ When you don't need access to the index then 'Control.Lens.Fold.foldrOf' is more flexible in what it accepts.------ @'Control.Lens.Fold.foldrOf' l ≡ 'ifoldrOf' l '.' 'const'@------ @--- 'ifoldrOf' :: 'IndexedGetter' i a c          -> (i -> c -> e -> e) -> e -> a -> e--- 'ifoldrOf' :: 'IndexedFold' i a c            -> (i -> c -> e -> e) -> e -> a -> e--- 'ifoldrOf' :: 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c      -> (i -> c -> e -> e) -> e -> a -> e--- 'ifoldrOf' :: 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c -> (i -> c -> e -> e) -> e -> a -> e--- @-ifoldrOf :: IndexedGetting i (Endo e) a b c d -> (i -> c -> e -> e) -> e -> a -> e-ifoldrOf l f z t = appEndo (ifoldMapOf l (\i -> Endo . f i) t) z-{-# INLINE ifoldrOf #-}---- |--- Left-associative fold of the parts of a structure that are viewed through an 'IndexedFold' or 'Control.Lens.IndexedTraversal.IndexedTraversal' with--- access to the index @i@.------ When you don't need access to the index then 'Control.Lens.Fold.foldlOf' is more flexible in what it accepts.------ @'Control.Lens.Fold.foldlOf' l ≡ 'ifoldlOf' l '.' 'const'@------ @--- 'ifoldlOf' :: 'IndexedGetter' i a c          -> (i -> e -> c -> e) -> e -> a -> e--- 'ifoldlOf' :: 'IndexedFold' i a c            -> (i -> e -> c -> e) -> e -> a -> e--- 'ifoldlOf' :: 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c      -> (i -> e -> c -> e) -> e -> a -> e--- 'ifoldlOf' :: 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c -> (i -> e -> c -> e) -> e -> a -> e--- @-ifoldlOf :: IndexedGetting i (Dual (Endo e)) a b c d -> (i -> e -> c -> e) -> e -> a -> e-ifoldlOf l f z t = appEndo (getDual (ifoldMapOf l (\i -> Dual . Endo . flip (f i)) t)) z-{-# INLINE ifoldlOf #-}---- |--- Return whether or not any element viewed through an 'IndexedFold' or 'Control.Lens.IndexedTraversal.IndexedTraversal'--- satisfy a predicate, with access to the index @i@.------ When you don't need access to the index then 'Control.Lens.Fold.anyOf' is more flexible in what it accepts.------ @'Control.Lens.Fold.anyOf' l ≡ 'ianyOf' l '.' 'const'@------ @--- 'ianyOf' :: 'IndexedGetter' i a c          -> (i -> c -> 'Bool') -> a -> 'Bool'--- 'ianyOf' :: 'IndexedFold' i a c            -> (i -> c -> 'Bool') -> a -> 'Bool'--- 'ianyOf' :: 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c      -> (i -> c -> 'Bool') -> a -> 'Bool'--- 'ianyOf' :: 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c -> (i -> c -> 'Bool') -> a -> 'Bool'--- @-ianyOf :: IndexedGetting i Any a b c d -> (i -> c -> Bool) -> a -> Bool-ianyOf l f = getAny . ifoldMapOf l (\i -> Any . f i)-{-# INLINE ianyOf #-}---- |--- Return whether or not all elements viewed through an 'IndexedFold' or 'Control.Lens.IndexedTraversal.IndexedTraversal'--- satisfy a predicate, with access to the index @i@.------ When you don't need access to the index then 'Control.Lens.Fold.allOf' is more flexible in what it accepts.------ @'Control.Lens.Fold.allOf' l ≡ 'iallOf' l '.' 'const'@------ @--- 'iallOf' :: 'IndexedGetter' i a c          -> (i -> c -> 'Bool') -> a -> 'Bool'--- 'iallOf' :: 'IndexedFold' i a c            -> (i -> c -> 'Bool') -> a -> 'Bool'--- 'iallOf' :: 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c      -> (i -> c -> 'Bool') -> a -> 'Bool'--- 'iallOf' :: 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c -> (i -> c -> 'Bool') -> a -> 'Bool'--- @-iallOf :: IndexedGetting i All a b c d -> (i -> c -> Bool) -> a -> Bool-iallOf l f = getAll . ifoldMapOf l (\i -> All . f i)-{-# INLINE iallOf #-}---- |--- Traverse the targets of an 'IndexedFold' or 'Control.Lens.IndexedTraversal.IndexedTraversal' with access to the index @i@, discarding the results.------ When you don't need access to the index then 'Control.Lens.Fold.traverseOf_' is more flexible in what it accepts.------ @'Control.Lens.Fold.traverseOf_' l ≡ 'itraverseOf' l '.' 'const'@------ @--- 'itraverseOf_' :: 'Functor' f     => 'IndexedGetter' i a c          -> (i -> c -> f e) -> a -> f ()--- 'itraverseOf_' :: 'Applicative' f => 'IndexedFold' i a c            -> (i -> c -> f e) -> a -> f ()--- 'itraverseOf_' :: 'Functor' f     => 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c      -> (i -> c -> f e) -> a -> f ()--- 'itraverseOf_' :: 'Applicative' f => 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c -> (i -> c -> f e) -> a -> f ()--- @-itraverseOf_ :: Functor f => IndexedGetting i (Traversed f) a b c d -> (i -> c -> f e) -> a -> f ()-itraverseOf_ l f = getTraversed . ifoldMapOf l (\i -> Traversed . void . f i)-{-# INLINE itraverseOf_ #-}---- |--- Traverse the targets of an 'IndexedFold' or 'Control.Lens.IndexedTraversal.IndexedTraversal' with access to the index, discarding the results--- (with the arguments flipped).------ @'iforOf_' ≡ 'flip' '.' 'itraverseOf_'@------ When you don't need access to the index then 'Control.Lens.Fold.forOf_' is more flexible in what it accepts.------ @'Control.Lens.Fold.forOf_' l a ≡ 'iforOf_' l a '.' 'const'@------ @--- 'iforOf_' :: 'Functor' f     => 'IndexedGetter' i a c          -> a -> (i -> c -> f e) -> f ()--- 'iforOf_' :: 'Applicative' f => 'IndexedFold' i a c            -> a -> (i -> c -> f e) -> f ()--- 'iforOf_' :: 'Functor' f     => 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c      -> a -> (i -> c -> f e) -> f ()--- 'iforOf_' :: 'Applicative' f => 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c -> a -> (i -> c -> f e) -> f ()--- @-iforOf_ :: Functor f => IndexedGetting i (Traversed f) a b c d -> a -> (i -> c -> f e) -> f ()-iforOf_ = flip . itraverseOf_-{-# INLINE iforOf_ #-}---- |--- Run monadic actions for each target of an 'IndexedFold' or 'Control.Lens.IndexedTraversal.IndexedTraversal' with access to the index,--- discarding the results.------ When you don't need access to the index then 'Control.Lens.Fold.mapMOf_' is more flexible in what it accepts.------ @'Control.Lens.Fold.mapMOf_' l ≡ 'imapMOf' l '.' 'const'@------ @--- 'imapMOf_' :: 'Monad' m => 'IndexedGetter' i a c          -> (i -> c -> m e) -> a -> m ()--- 'imapMOf_' :: 'Monad' m => 'IndexedFold' i a c            -> (i -> c -> m e) -> a -> m ()--- 'imapMOf_' :: 'Monad' m => 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c      -> (i -> c -> m e) -> a -> m ()--- 'imapMOf_' :: 'Monad' m => 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c -> (i -> c -> m e) -> a -> m ()--- @-imapMOf_ :: Monad m => IndexedGetting i (Sequenced m) a b c d -> (i -> c -> m e) -> a -> m ()-imapMOf_ l f = getSequenced . ifoldMapOf l (\i -> Sequenced . liftM skip . f i)-{-# INLINE imapMOf_ #-}--skip :: a -> ()-skip _ = ()-{-# INLINE skip #-}---- |--- Run monadic actions for each target of an 'IndexedFold' or 'Control.Lens.IndexedTraversal.IndexedTraversal' with access to the index,--- discarding the results (with the arguments flipped).------ @'iforMOf_' ≡ 'flip' '.' 'imapMOf_'@------ When you don't need access to the index then 'Control.Lens.Fold.forMOf_' is more flexible in what it accepts.------ @'Control.Lens.Fold.forMOf_' l a ≡ 'iforMOf' l a '.' 'const'@------ @--- 'iforMOf_' :: 'Monad' m => 'IndexedGetter' i a c          -> a -> (i -> c -> m e) -> m ()--- 'iforMOf_' :: 'Monad' m => 'IndexedFold' i a c            -> a -> (i -> c -> m e) -> m ()--- 'iforMOf_' :: 'Monad' m => 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c      -> a -> (i -> c -> m e) -> m ()--- 'iforMOf_' :: 'Monad' m => 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c -> a -> (i -> c -> m e) -> m ()--- @-iforMOf_ :: Monad m => IndexedGetting i (Sequenced m) a b c d -> a -> (i -> c -> m e) -> m ()-iforMOf_ = flip . imapMOf_-{-# INLINE iforMOf_ #-}---- |--- Concatenate the results of a function of the elements of an 'IndexedFold' or 'Control.Lens.IndexedTraversal.IndexedTraversal'--- with access to the index.------ When you don't need access to the index then 'Control.Lens.Fold.concatMapOf'  is more flexible in what it accepts.------ @--- 'Control.Lens.Fold.concatMapOf' l ≡ 'iconcatMapOf' l '.' 'const'--- 'iconcatMapOf' ≡ 'ifoldMapOf'--- @------ @--- 'iconcatMapOf' :: 'IndexedGetter' i a c          -> (i -> c -> [e]) -> a -> [e]--- 'iconcatMapOf' :: 'IndexedFold' i a c            -> (i -> c -> [e]) -> a -> [e]--- 'iconcatMapOf' :: 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c      -> (i -> c -> [e]) -> a -> [e]--- 'iconcatMapOf' :: 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c -> (i -> c -> [e]) -> a -> [e]--- @-iconcatMapOf :: IndexedGetting i [e] a b c d -> (i -> c -> [e]) -> a -> [e]-iconcatMapOf = ifoldMapOf-{-# INLINE iconcatMapOf #-}---- | The 'findOf' function takes an 'IndexedFold' or 'Control.Lens.IndexedTraversal.IndexedTraversal', a predicate that is also--- supplied the index, a structure and returns the left-most element of the structure--- matching the predicate, or 'Nothing' if there is no such element.------ When you don't need access to the index then 'Control.Lens.Fold.findOf' is more flexible in what it accepts.------ @'Control.Lens.Fold.findOf' l ≡ 'ifindOf' l '.' 'const'@------ @--- 'ifindOf' :: 'IndexedGetter' a c          -> (i -> c -> 'Bool') -> a -> 'Maybe' (i, c)--- 'ifindOf' :: 'IndexedFold' a c            -> (i -> c -> 'Bool') -> a -> 'Maybe' (i, c)--- 'ifindOf' :: 'Control.Lens.IndexedLens.SimpleIndexedLens' a c      -> (i -> c -> 'Bool') -> a -> 'Maybe' (i, c)--- 'ifindOf' :: 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' a c -> (i -> c -> 'Bool') -> a -> 'Maybe' (i, c)--- @-ifindOf :: IndexedGetting i (First (i, c)) a b c d -> (i -> c -> Bool) -> a -> Maybe (i, c)-ifindOf l p = getFirst . ifoldMapOf l step where-  step i c-    | p i c     = First $ Just (i, c)-    | otherwise = First Nothing-{-# INLINE ifindOf #-}---- | /Strictly/ fold right over the elements of a structure with an index.------ When you don't need access to the index then 'Control.Lens.Fold.foldrOf'' is more flexible in what it accepts.------ @'Control.Lens.Fold.foldrOf'' l ≡ 'ifoldrOf'' l '.' 'const'@------ @--- 'ifoldrOf'' :: 'IndexedGetter' i a c          -> (i -> c -> e -> e) -> e -> a -> e--- 'ifoldrOf'' :: 'IndexedFold' i a c            -> (i -> c -> e -> e) -> e -> a -> e--- 'ifoldrOf'' :: 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c      -> (i -> c -> e -> e) -> e -> a -> e--- 'ifoldrOf'' :: 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c -> (i -> c -> e -> e) -> e -> a -> e--- @-ifoldrOf' :: IndexedGetting i (Dual (Endo (e -> e))) a b c d -> (i -> c -> e -> e) -> e -> a -> e-ifoldrOf' l f z0 xs = ifoldlOf l f' id xs z0-  where f' i k x z = k $! f i x z-{-# INLINE ifoldrOf' #-}---- | Fold over the elements of a structure with an index, associating to the left, but /strictly/.------ When you don't need access to the index then 'Control.Lens.Fold.foldlOf'' is more flexible in what it accepts.------ @'Control.Lens.Fold.foldlOf'' l ≡ 'ifoldlOf'' l '.' 'const'@------ @--- 'ifoldlOf'' :: 'IndexedGetter' i a c            -> (i -> e -> c -> e) -> e -> a -> e--- 'ifoldlOf'' :: 'IndexedFold' i a c              -> (i -> e -> c -> e) -> e -> a -> e--- 'ifoldlOf'' :: 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c        -> (i -> e -> c -> e) -> e -> a -> e--- 'ifoldlOf'' :: 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c   -> (i -> e -> c -> e) -> e -> a -> e--- @-ifoldlOf' :: IndexedGetting i (Endo (e -> e)) a b c d -> (i -> e -> c -> e) -> e -> a -> e-ifoldlOf' l f z0 xs = ifoldrOf l f' id xs z0-  where f' i x k z = k $! f i z x-{-# INLINE ifoldlOf' #-}---- | Monadic fold right over the elements of a structure with an index.------ When you don't need access to the index then 'Control.Lens.Fold.foldrMOf' is more flexible in what it accepts.------ @'Control.Lens.Fold.foldrMOf' l ≡ 'ifoldrMOf' l '.' 'const'@------ @--- 'ifoldrMOf' :: 'Monad' m => 'IndexedGetter' i a c          -> (i -> c -> e -> m e) -> e -> a -> e--- 'ifoldrMOf' :: 'Monad' m => 'IndexedFold' i a c            -> (i -> c -> e -> m e) -> e -> a -> e--- 'ifoldrMOf' :: 'Monad' m => 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c      -> (i -> c -> e -> m e) -> e -> a -> e--- 'ifoldrMOf' :: 'Monad' m => 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c -> (i -> c -> e -> m e) -> e -> a -> e--- @-ifoldrMOf :: Monad m => IndexedGetting i (Dual (Endo (e -> m e))) a b c d -> (i -> c -> e -> m e) -> e -> a -> m e-ifoldrMOf l f z0 xs = ifoldlOf l f' return xs z0-  where f' i k x z = f i x z >>= k-{-# INLINE ifoldrMOf #-}---- | Monadic fold over the elements of a structure with an index, associating to the left.------ When you don't need access to the index then 'Control.Lens.Fold.foldlMOf' is more flexible in what it accepts.------ @'Control.Lens.Fold.foldlMOf' l ≡ 'ifoldlMOf' l '.' 'const'@------ @--- 'ifoldlOf'' :: 'Monad' m => 'IndexedGetter' i a c            -> (i -> e -> c -> m e) -> e -> a -> e--- 'ifoldlOf'' :: 'Monad' m => 'IndexedFold' i a c              -> (i -> e -> c -> m e) -> e -> a -> e--- 'ifoldlOf'' :: 'Monad' m => 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c        -> (i -> e -> c -> m e) -> e -> a -> e--- 'ifoldlOf'' :: 'Monad' m => 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c   -> (i -> e -> c -> m e) -> e -> a -> e--- @-ifoldlMOf :: Monad m => IndexedGetting i (Endo (e -> m e)) a b c d -> (i -> e -> c -> m e) -> e -> a -> m e-ifoldlMOf l f z0 xs = ifoldrOf l f' return xs z0-  where f' i x k z = f i z x >>= k-{-# INLINE ifoldlMOf #-}---- | Extract the key-value pairs from a structure.------ When you don't need access to the indices in the result, then 'Control.Lens.Fold.toListOf' is more flexible in what it accepts.------ @'Control.Lens.Fold.toListOf' l ≡ 'map' 'fst' '.' 'itoListOf' l@------ @--- 'itoListOf' :: 'IndexedGetter' i a c          -> a -> [(i,c)]--- 'itoListOf' :: 'IndexedFold' i a c            -> a -> [(i,c)]--- 'itoListOf' :: 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c      -> a -> [(i,c)]--- 'itoListOf' :: 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c -> a -> [(i,c)]--- @-itoListOf :: IndexedGetting i [(i,c)] a b c d -> a -> [(i,c)]-itoListOf l = ifoldMapOf l (\i c -> [(i,c)])-{-# INLINE itoListOf #-}------------------------------------------------------------------------------------ Converting to Folds------------------------------------------------------------------------------------ | Transform an indexed fold into a fold of both the indices and the values.------ @--- 'withIndices' :: 'IndexedFold' i a c             -> 'Fold' a (i, c)--- 'withIndices' :: 'Simple' 'IndexedLens' i a c      -> 'Getter' a (i, c)--- 'withIndices' :: 'Simple' 'IndexedTraversal' i a c -> 'Fold' a (i, c)--- @------ All 'Fold' operations are safe, and comply with the laws. However,------ Passing this an 'IndexedTraversal' will still allow many--- 'Traversal' combinators to type check on the result, but the result--- can only be legally traversed by operations that do not edit the indices.------ @--- 'withIndices' :: 'IndexedTraversal' i a b c d -> 'Traversal' a b (i, c) (j, d)--- @------ Change made to the indices will be discarded.-withIndicesOf :: Functor f => Overloaded (Index i) f a b c d -> LensLike f a b (i, c) (j, d)-withIndicesOf l f = withIndex l (\i c -> snd <$> f (i,c))-{-# INLINE withIndicesOf #-}---- | Transform an indexed fold into a fold of the indices.------ @--- 'indices' :: 'IndexedFold' i a c             -> 'Fold' a i--- 'indices' :: 'Simple' 'IndexedLens' i a c      -> 'Getter' a i--- 'indices' :: 'Simple' 'IndexedTraversal' i a c -> 'Fold' a i--- @-indicesOf :: Gettable f => Overloaded (Index i) f a b c c -> LensLike f a b i j-indicesOf l f = withIndex l (const . coerce . f)-{-# INLINE indicesOf #-}------------------------------------------------------------------------------------ Converting to Folds------------------------------------------------------------------------------------ | Obtain an 'IndexedFold' by filtering a 'Control.Lens.IndexedLens.IndexedLens', 'IndexedGetter', 'IndexedFold' or 'Control.Lens.IndexedTraversal.IndexedTraversal'.-ifiltered :: (Gettable f, Applicative f, Indexed i k) => (i -> c -> Bool) -> Index i (c -> f c) (a -> f b) -> k (c -> f c) (a -> f b)-ifiltered p l = index $ \ f -> withIndex l $ \ i c -> if p i c then f i c else noEffect-{-# INLINE ifiltered #-}---- | Obtain an 'IndexedFold' by taking elements from another 'IndexedFold', 'Control.Lens.IndexedLens.IndexedLens', 'IndexedGetter' or 'Control.Lens.IndexedTraversal.IndexedTraversal' while a predicate holds.-itakingWhile :: (Gettable f, Applicative f, Indexed i k)-            => (i -> c -> Bool)-            -> IndexedGetting i (Endo (f a)) a a c c-            -> k (c -> f c) (a -> f a)-itakingWhile p l = index $ \ f -> ifoldrOf l (\i a r -> if p i a then f i a *> r else noEffect) noEffect-{-# INLINE itakingWhile #-}----- | Obtain an 'IndexedFold' by dropping elements from another 'IndexedFold', 'Control.Lens.IndexedLens.IndexedLens', 'IndexedGetter' or 'Control.Lens.IndexedTraversal.IndexedTraversal' while a predicate holds.-idroppingWhile :: (Gettable f, Applicative f, Indexed i k)-              => (i -> c -> Bool)-              -> IndexedGetting i (Endo (f a)) a a c c-              -> k (c -> f c) (a -> f a)-idroppingWhile p l = index $ \f -> ifoldrOf l (\i a r -> if p i a then r else f i a *> r) noEffect-{-# INLINE idroppingWhile #-}----------------------------------------------------------------------------------- Reifying Indexed Folds----------------------------------------------------------------------------------- | Useful for storage.-newtype ReifiedIndexedFold i a c = ReifyIndexedFold { reflectIndexedFold :: IndexedFold i a c }
− src/Control/Lens/IndexedGetter.hs
@@ -1,35 +0,0 @@-{-# LANGUAGE Rank2Types #-}-{-# LANGUAGE MultiParamTypeClasses #-}--------------------------------------------------------------------------------- |--- Module      :  Control.Lens.IndexedGetter--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  experimental--- Portability :  rank 2 types, MPTCs---------------------------------------------------------------------------------module Control.Lens.IndexedGetter-  (-  -- * Indexed Folds-    IndexedGetter-  , IndexedGetting-  , ReifiedIndexedGetter(..)-  ) where--import Control.Lens.Indexed-import Control.Lens.Internal----------------------------------------------------------------------------------- Indexed Getters----------------------------------------------------------------------------------- | Every 'IndexedGetter' is a valid 'Control.Lens.IndexedFold.IndexedFold' and 'Getter'.-type IndexedGetter i a c = forall k f. (Indexed i k, Gettable f) => k (c -> f c) (a -> f a)---- | Used to consume an 'Control.Lens.IndexedFold.IndexedFold'.-type IndexedGetting i m a b c d = Index i (c -> Accessor m d) (a -> Accessor m b)---- | Useful for storage.-newtype ReifiedIndexedGetter i a c = ReifyIndexedGetter { reflectIndexedGetter :: IndexedGetter i a c }
− src/Control/Lens/IndexedLens.hs
@@ -1,195 +0,0 @@-{-# LANGUAGE CPP #-}-{-# LANGUAGE Rank2Types #-}-{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FunctionalDependencies #-}--#ifndef MIN_VERSION_mtl-#define MIN_VERSION_mtl(x,y,z) 1-#endif---------------------------------------------------------------------------------- |--- Module      :  Control.Lens.IndexedLens--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  rank 2 types, MPTCs, TFs, flexible---------------------------------------------------------------------------------module Control.Lens.IndexedLens-  (-  -- * Indexed Lenses-    IndexedLens-  -- * Common Indexed Lenses-  , At(..)-  , Contains(..)-  -- * Indexed Lens Combinators-  , (%%@~)-  , (<%@~)-  , (%%@=)-  , (<%@=)-  -- * Storing Indexed Lenses-  , ReifiedIndexedLens(..)-  -- * Simple-  , SimpleIndexedLens-  , SimpleReifiedIndexedLens-  ) where--import Control.Applicative-import Control.Lens.Indexed-import Control.Lens.Type-import Control.Monad.State.Class as State-import Data.Hashable-import Data.HashMap.Lazy as HashMap-import Data.IntMap as IntMap-import Data.Map as Map--import Data.HashSet as HashSet-import Data.IntSet as IntSet-import Data.Set as Set---- $setup--- >>> import Control.Lens--infixr 4 %%@~, <%@~-infix  4 %%@=, <%@=---- | Every 'IndexedLens' is a valid 'Lens' and a valid 'Control.Lens.IndexedTraversal.IndexedTraversal'.-type IndexedLens i a b c d = forall f k. (Indexed i k, Functor f) => k (c -> f d) (a -> f b)---- | @type 'SimpleIndexedLens' i = 'Simple' ('IndexedLens' i)@-type SimpleIndexedLens i a b = IndexedLens i a a b b---- | Adjust the target of an 'IndexedLens' returning the intermediate result, or--- adjust all of the targets of an 'Control.Lens.IndexedTraversal.IndexedTraversal' and return a monoidal summary--- along with the answer.------ @l '<%~' f = l '<%@~' 'const' f@------ When you do not need access to the index then ('<%~') is more liberal in what it can accept.------ If you do not need the intermediate result, you can use ('Control.Lens.Type.%@~') or even ('Control.Lens.Type.%~').------ @--- ('<%@~') ::             'IndexedLens' i a b c d -> (i -> c -> d) -> a -> (d, b)--- ('<%@~') :: 'Monoid' d => 'Control.Lens.IndexedTraversal.IndexedTraversal' i a b c d -> (i -> c -> d) -> a -> (d, b)--- @-(<%@~) :: Overloaded (Index i) ((,)d) a b c d -> (i -> c -> d) -> a -> (d, b)-l <%@~ f = withIndex l $ \i c -> let d = f i c in (d, d)-{-# INLINE (<%@~) #-}---- | Adjust the target of an 'IndexedLens' returning a supplementary result, or--- adjust all of the targets of an 'Control.Lens.IndexedTraversal.IndexedTraversal' and return a monoidal summary--- of the supplementary results and the answer.------ @('%%@~') = 'withIndex'@------ @--- ('%%@~') :: 'Functor' f => 'IndexedLens' i a b c d      -> (i -> c -> f d) -> a -> f b--- ('%%@~') :: 'Functor' f => 'Control.Lens.IndexedTraversal.IndexedTraversal' i a b c d -> (i -> c -> f d) -> a -> f b--- @------ In particular, it is often useful to think of this function as having one of these even more--- restrictive type signatures------ @--- ('%%@~') ::             'IndexedLens' i a b c d      -> (i -> c -> (e, d)) -> a -> (e, b)--- ('%%@~') :: 'Monoid' e => 'Control.Lens.IndexedTraversal.IndexedTraversal' i a b c d -> (i -> c -> (e, d)) -> a -> (e, b)--- @-(%%@~) :: Overloaded (Index i) f a b c d -> (i -> c -> f d) -> a -> f b-(%%@~) = withIndex-{-# INLINE (%%@~) #-}---- | Adjust the target of an 'IndexedLens' returning a supplementary result, or--- adjust all of the targets of an 'Control.Lens.IndexedTraversal.IndexedTraversal' within the current state, and--- return a monoidal summary of the supplementary results.------ @l '%%@=' f = 'state' (l '%%@~' f)@------ @--- ('%%@=') :: 'MonadState' a m                'IndexedLens' i a a c d      -> (i -> c -> (e, d)) -> a -> m e--- ('%%@=') :: ('MonadState' a m, 'Monoid' e) => 'Control.Lens.IndexedTraversal.IndexedTraversal' i a a c d -> (i -> c -> (e, d)) -> a -> m e--- @-(%%@=) :: MonadState a m => Overloaded (Index i) ((,)e) a a c d -> (i -> c -> (e, d)) -> m e-#if MIN_VERSION_mtl(2,1,0)-l %%@= f = State.state (l %%@~ f)-#else-l %%@= f = do-  (e, d) <- State.gets (l %%@~ f)-  State.put d-  return e-#endif-{-# INLINE (%%@=) #-}---- | Adjust the target of an 'IndexedLens' returning the intermediate result, or--- adjust all of the targets of an 'Control.Lens.IndexedTraversal.IndexedTraversal' within the current state, and--- return a monoidal summary of the intermediate results.------ @--- ('<%@=') :: 'MonadState' a m                'IndexedLens' i a a c d      -> (i -> c -> d) -> a -> m d--- ('<%@=') :: ('MonadState' a m, 'Monoid' e) => 'Control.Lens.IndexedTraversal.IndexedTraversal' i a a c d -> (i -> c -> d) -> a -> m d--- @-(<%@=) :: MonadState a m => Overloaded (Index i) ((,)d) a a c d -> (i -> c -> d) -> m d-l <%@= f = l %%@= \ i c -> let d = f i c in (d, d)-{-# INLINE (<%@=) #-}---- | Provides an 'IndexedLens' that can be used to read, write or delete the value associated with a key in a map-like container.-class At k m | m -> k where-  -- |-  -- >>> Map.fromList [(1,"hello")] ^.at 1-  -- Just "hello"-  ---  -- >>> at 1 .~ Just "hello" $ Map.empty-  -- fromList [(1,"hello")]-  at :: k -> SimpleIndexedLens k (m v) (Maybe v)--instance At Int IntMap where-  at k = index $ \ f m -> (`go` m) <$> f k (IntMap.lookup k m) where-    go Nothing   = IntMap.delete k-    go (Just v') = IntMap.insert k v'-  {-# INLINE at #-}--instance Ord k => At k (Map k) where-  at k = index $ \ f m -> (`go` m) <$> f k (Map.lookup k m) where-    go Nothing   = Map.delete k-    go (Just v') = Map.insert k v'-  {-# INLINE at #-}--instance (Eq k, Hashable k) => At k (HashMap k) where-  at k = index $ \ f m -> (`go` m) <$> f k (HashMap.lookup k m) where-    go Nothing   = HashMap.delete k-    go (Just v') = HashMap.insert k v'-  {-# INLINE at #-}---- | Provides an 'IndexedLens' that can be used to read, write or delete a member of a set-like container-class Contains k m | m -> k where-  -- |-  -- >>> contains 3 .~ False $ IntSet.fromList [1,2,3,4]-  -- fromList [1,2,4]-  contains :: k -> SimpleIndexedLens k m Bool--instance Contains Int IntSet where-  contains k = index $ \ f s -> (\b -> if b then IntSet.insert k s else IntSet.delete k s) <$> f k (IntSet.member k s)-  {-# INLINE contains #-}--instance Ord k => Contains k (Set k) where-  contains k = index $ \ f s -> (\b -> if b then Set.insert k s else Set.delete k s) <$> f k (Set.member k s)-  {-# INLINE contains #-}--instance (Eq k, Hashable k) => Contains k (HashSet k) where-  contains k = index $ \ f s -> (\b -> if b then HashSet.insert k s else HashSet.delete k s) <$> f k (HashSet.member k s)-  {-# INLINE contains #-}----------------------------------------------------------------------------------- Reifying Indexed Lenses----------------------------------------------------------------------------------- | Useful for storage.-newtype ReifiedIndexedLens i a b c d = ReifyIndexedLens { reflectIndexedLens :: IndexedLens i a b c d }---- | @type 'SimpleIndexedLens' i = 'Simple' ('ReifiedIndexedLens' i)@-type SimpleReifiedIndexedLens i a b = ReifiedIndexedLens i a a b b
− src/Control/Lens/IndexedSetter.hs
@@ -1,144 +0,0 @@-{-# LANGUAGE Rank2Types #-}-{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE FlexibleContexts #-}--------------------------------------------------------------------------------- |--- Module      :  Control.Lens.IndexedSetter--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  rank 2 types, MPTCs, TFs, flexible---------------------------------------------------------------------------------module Control.Lens.IndexedSetter-  (-  -- * Indexed Setter-    IndexedSetter-  , imapOf, iover-  , isets-  , (%@~)-  , (%@=)-  -- * Storing Indexed Setters-  , ReifiedIndexedSetter(..)-  -- * Simple-  , SimpleIndexedSetter-  , SimpleReifiedIndexedSetter-  ) where--import Control.Applicative-import Control.Lens.Indexed-import Control.Lens.Internal-import Control.Lens.Type-import Control.Monad.State.Class as State--infixr 4 %@~-infix  4 %@=---- | Every 'IndexedSetter' is a valid 'Setter'------ The 'Control.Lens.Setter.Setter' laws are still required to hold.-type IndexedSetter i a b c d = forall f k. (Indexed i k, Settable f) => k (c -> f d) (a -> f b)---- |--- @type 'SimpleIndexedSetter' i = 'Simple' ('IndexedSetter' i)@-type SimpleIndexedSetter i a b = IndexedSetter i a a b b---- | Map with index.------ When you do not need access to the index, then 'mapOf' is more liberal in what it can accept.------ @'Control.Lens.Setter.mapOf' l ≡ 'imapOf' l '.' 'const'@------ @--- 'imapOf' :: 'IndexedSetter' i a b c d    -> (i -> c -> d) -> a -> b--- 'imapOf' :: 'Control.Lens.IndexedLens.IndexedLens' i a b c d      -> (i -> c -> d) -> a -> b--- 'imapOf' :: 'Control.Lens.IndexedTraversal.IndexedTraversal' i a b c d -> (i -> c -> d) -> a -> b--- @-imapOf :: Overloaded (Index i) Mutator a b c d -> (i -> c -> d) -> a -> b-imapOf l f = runMutator . withIndex l (\i -> Mutator . f i)-{-# INLINE imapOf #-}---- | Map with index. This is an alias for 'imapOf'.------ When you do not need access to the index, then 'over' is more liberal in what it can accept.------ @'Control.Lens.Setter.over' l ≡ 'iover' l '.' 'const'@------ @--- 'iover' :: 'IndexedSetter' i a b c d    -> (i -> c -> d) -> a -> b--- 'iover' :: 'Control.Lens.IndexedLens.IndexedLens' i a b c d      -> (i -> c -> d) -> a -> b--- 'iover' :: 'Control.Lens.IndexedTraversal.IndexedTraversal' i a b c d -> (i -> c -> d) -> a -> b--- @-iover :: Overloaded (Index i) Mutator a b c d -> (i -> c -> d) -> a -> b-iover l f = runMutator . withIndex l (\i -> Mutator . f i)-{-# INLINE iover #-}---- | Build an 'IndexedSetter' from an 'imap'-like function.------ Your supplied function @f@ is required to satisfy:------ @--- f 'id' ≡ 'id'--- f g '.' f h ≡ f (g '.' h)--- @------ Equational reasoning:------ @--- 'isets' '.' 'iover' ≡ 'id'--- 'iover' '.' 'isets' ≡ 'id'--- @------ Another way to view 'sets' is that it takes a \"semantic editor combinator\"--- and transforms it into a 'Setter'.-isets :: ((i -> c -> d) -> a -> b) -> IndexedSetter i a b c d-isets f = index $ \ g -> pure . f (\i -> untainted . g i)-{-# INLINE isets #-}---- | Adjust every target of an 'IndexedSetter', 'Control.Lens.IndexedLens.IndexedLens' or 'Control.Lens.IndexedTraversal.IndexedTraversal'--- with access to the index.------ @('%@~') ≡ 'imapOf'@------ When you do not need access to the index then ('%@~') is more liberal in what it can accept.------ @l 'Control.Lens.Setter.%~' f ≡ l '%@~' 'const' f@------ @--- ('%@~') :: 'IndexedSetter' i a b c d    -> (i -> c -> d) -> a -> b--- ('%@~') :: 'Control.Lens.IndexedLens.IndexedLens' i a b c d      -> (i -> c -> d) -> a -> b--- ('%@~') :: 'Control.Lens.IndexedTraversal.IndexedTraversal' i a b c d -> (i -> c -> d) -> a -> b--- @-(%@~) :: Overloaded (Index i) Mutator a b c d -> (i -> c -> d) -> a -> b-l %@~ f = runMutator . withIndex l (\i -> Mutator . f i)-{-# INLINE (%@~) #-}---- | Adjust every target in the current state of an 'IndexedSetter', 'Control.Lens.IndexedLens.IndexedLens' or 'Control.Lens.IndexedTraversal.IndexedTraversal'--- with access to the index.------ When you do not need access to the index then ('Control.Lens.Setter.%=') is more liberal in what it can accept.------ @l 'Control.Lens.Setter.%=' f ≡ l '%@=' 'const' f@------ @--- ('%@=') :: 'MonadState' a m => 'IndexedSetter' i a a c d    -> (i -> c -> d) -> m ()--- ('%@=') :: 'MonadState' a m => 'Control.Lens.IndexedLens.IndexedLens' i a a c d      -> (i -> c -> d) -> m ()--- ('%@=') :: 'MonadState' a m => 'Control.Lens.IndexedTraversal.IndexedTraversal' i a b c d -> (i -> c -> d) -> m ()--- @-(%@=) :: MonadState a m => Overloaded (Index i) Mutator a a c d -> (i -> c -> d) -> m ()-l %@= f = State.modify (l %@~ f)-{-# INLINE (%@=) #-}----------------------------------------------------------------------------------- Reifying Indexed Setters----------------------------------------------------------------------------------- | Useful for storage.-newtype ReifiedIndexedSetter i a b c d = ReifyIndexedSetter { reflectIndexedSetter :: IndexedSetter i a b c d }---- | @type 'SimpleIndexedSetter' i = 'Simple' ('ReifiedIndexedSetter' i)@-type SimpleReifiedIndexedSetter i a b = ReifiedIndexedSetter i a a b b-
− src/Control/Lens/IndexedTraversal.hs
@@ -1,259 +0,0 @@-{-# LANGUAGE CPP #-}-{-# LANGUAGE Rank2Types #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FunctionalDependencies #-}--#ifndef MIN_VERSION_containers-#define MIN_VERSION_containers(x,y,z) 1-#endif--------------------------------------------------------------------------------- |--- Module      :  Control.Lens.IndexedTraversal--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  rank 2 types, MPTCs, TFs, flexible---------------------------------------------------------------------------------module Control.Lens.IndexedTraversal-  (-  -- * Indexed Traversals-    IndexedTraversal--  -- * Common Indexed Traversals-  , traverseAt-  , iwhereOf-  , value-  , TraverseMin(..)-  , TraverseMax(..)--  -- * Indexed Traversal Combinators-  , itraverseOf-  , iforOf-  , imapMOf-  , iforMOf-  , imapAccumROf-  , imapAccumLOf--  -- * Storing Indexed Traversals-  , ReifiedIndexedTraversal(..)--  -- * Simple-  , SimpleIndexedTraversal-  , SimpleReifiedIndexedTraversal-  ) where--import Control.Applicative-import Control.Applicative.Backwards-import Control.Lens.Indexed-import Control.Lens.IndexedLens-import Control.Lens.Type-import Control.Monad.Trans.State.Lazy as Lazy-import Data.Traversable-import Data.IntMap as IntMap-import Data.Map as Map---- $setup--- >>> import Control.Lens----------------------------------------------------------------------------------- Indexed Traversals----------------------------------------------------------------------------------- | Every indexed traversal is a valid 'Control.Lens.Traversal.Traversal' or 'Control.Lens.IndexedFold.IndexedFold'.------ The 'Indexed' constraint is used to allow an 'IndexedTraversal' to be used directly as a 'Control.Lens.Traversal.Traversal'.------ The 'Control.Lens.Traversal.Traversal' laws are still required to hold.-type IndexedTraversal i a b c d = forall f k. (Indexed i k, Applicative f) => k (c -> f d) (a -> f b)---- | @type 'SimpleIndexedTraversal' i = 'Simple' ('IndexedTraversal' i)@-type SimpleIndexedTraversal i a b = IndexedTraversal i a a b b---- | Traversal with an index.------ NB: When you don't need access to the index then you can just apply your 'IndexedTraversal'--- directly as a function!------ @--- 'itraverseOf' ≡ 'withIndex'--- 'Control.Lens.Traversal.traverseOf' l = 'itraverseOf' l '.' 'const' = 'id'--- @------ @--- 'itraverseOf' :: 'Control.Lens.IndexedLens.IndexedLens' i a b c d      -> (i -> c -> f d) -> a -> f b--- 'itraverseOf' :: 'IndexedTraversal' i a b c d -> (i -> c -> f d) -> a -> f b--- @-itraverseOf :: Overloaded (Index i) f a b c d -> (i -> c -> f d) -> a -> f b-itraverseOf = withIndex-{-# INLINE itraverseOf #-}---- |--- Traverse with an index (and the arguments flipped)------ @--- 'Control.Lens.Traversal.forOf' l a ≡ 'iforOf' l a '.' 'const'--- 'iforOf' ≡ 'flip' . 'itraverseOf'--- @------ @--- 'iforOf' :: 'Control.Lens.IndexedLens.IndexedLens' i a b c d      -> a -> (i -> c -> f d) -> f b--- 'iforOf' :: 'IndexedTraversal' i a b c d -> a -> (i -> c -> f d) -> f b--- @-iforOf :: Overloaded (Index i) f a b c d -> a -> (i -> c -> f d) -> f b-iforOf = flip . withIndex-{-# INLINE iforOf #-}---- | Map each element of a structure targeted by a lens to a monadic action,--- evaluate these actions from left to right, and collect the results, with access--- its position.------ When you don't need access to the index 'mapMOf' is more liberal in what it can accept.------ @'Control.Lens.Traversal.mapMOf' l ≡ 'imapMOf' l '.' 'const'@------ @--- 'imapMOf' :: 'Monad' m => 'Control.Lens.IndexedLens.IndexedLens'      i a b c d -> (i -> c -> m d) -> a -> m b--- 'imapMOf' :: 'Monad' m => 'IndexedTraversal' i a b c d -> (i -> c -> m d) -> a -> m b--- @-imapMOf :: Overloaded (Index i) (WrappedMonad m) a b c d -> (i -> c -> m d) -> a -> m b-imapMOf l f = unwrapMonad . withIndex l (\i -> WrapMonad . f i)-{-# INLINE imapMOf #-}---- | Map each element of a structure targeted by a lens to a monadic action,--- evaluate these actions from left to right, and collect the results, with access--- its position (and the arguments flipped).------ @--- 'Control.Lens.Traversal.forMOf' l a ≡ 'iforMOf' l a '.' 'const'--- 'iforMOf' ≡ 'flip' '.' 'imapMOf'--- @------ @--- 'iforMOf' :: 'Monad' m => 'Control.Lens.IndexedLens.IndexedLens' i a b c d      -> a -> (i -> c -> m d) -> m b--- 'iforMOf' :: 'Monad' m => 'IndexedTraversal' i a b c d -> a -> (i -> c -> m d) -> m b--- @-iforMOf :: Overloaded (Index i) (WrappedMonad m) a b c d -> a -> (i -> c -> m d) -> m b-iforMOf = flip . imapMOf-{-# INLINE iforMOf #-}---- | Generalizes 'Data.Traversable.mapAccumR' to an arbitrary 'IndexedTraversal' with access to the index.------ 'imapAccumROf' accumulates state from right to left.------ @'Control.Lens.Traversal.mapAccumROf' l ≡ 'imapAccumROf' l '.' 'const'@------ @--- 'imapAccumROf' :: 'Control.Lens.IndexedLens.IndexedLens' i a b c d      -> (i -> s -> c -> (s, d)) -> s -> a -> (s, b)--- 'imapAccumROf' :: 'IndexedTraversal' i a b c d -> (i -> s -> c -> (s, d)) -> s -> a -> (s, b)--- @-imapAccumROf :: Overloaded (Index i) (Lazy.State s) a b c d -> (i -> s -> c -> (s, d)) -> s -> a -> (s, b)-imapAccumROf l f s0 a = swap (Lazy.runState (withIndex l (\i c -> Lazy.state (\s -> swap (f i s c))) a) s0)-{-# INLINE imapAccumROf #-}---- | Generalizes 'Data.Traversable.mapAccumL' to an arbitrary 'IndexedTraversal' with access to the index.------ 'imapAccumLOf' accumulates state from left to right.------ @'Control.Lens.Traversal.mapAccumLOf' l ≡ 'imapAccumLOf' l '.' 'const'@------ @--- 'imapAccumLOf' :: 'Control.Lens.IndexedLens.IndexedLens' i a b c d      -> (i -> s -> c -> (s, d)) -> s -> a -> (s, b)--- 'imapAccumLOf' :: 'IndexedTraversal' i a b c d -> (i -> s -> c -> (s, d)) -> s -> a -> (s, b)--- @-imapAccumLOf :: Overloaded (Index i) (Backwards (Lazy.State s)) a b c d -> (i -> s -> c -> (s, d)) -> s -> a -> (s, b)-imapAccumLOf l f s0 a = swap (Lazy.runState (forwards (withIndex l (\i c -> Backwards (Lazy.state (\s -> swap (f i s c)))) a)) s0)-{-# INLINE imapAccumLOf #-}--swap :: (a,b) -> (b,a)-swap (a,b) = (b,a)-{-# INLINE swap #-}----------------------------------------------------------------------------------- Common Indexed Traversals----------------------------------------------------------------------------------- | Access the element of an 'IndexedTraversal' where the index matches a predicate.------ >>> over (iwhereOf (indexed traverse) (>0)) reverse $ ["He","was","stressed","o_O"]--- ["He","saw","desserts","O_o"]------ @--- 'iwhereOf' :: 'IndexedFold' i a b            -> (i -> 'Bool') -> 'IndexedFold' i a b--- 'iwhereOf' :: 'IndexedGetter' i a b          -> (i -> 'Bool') -> 'IndexedFold' i a b--- 'iwhereOf' :: 'SimpleIndexedLens' i a b      -> (i -> 'Bool') -> 'SimpleIndexedTraversal' i a b--- 'iwhereOf' :: 'SimpleIndexedTraversal' i a b -> (i -> 'Bool') -> 'SimpleIndexedTraversal' i a b--- 'iwhereOf' :: 'SimpleIndexedSetter' i a b    -> (i -> 'Bool') -> 'SimpleIndexedSetter' i a b--- @-iwhereOf :: (Indexed i k, Applicative f) => Overloaded (Index i) f a b c c -> (i -> Bool) -> Overloaded k f a b c c-iwhereOf l p = index $ \f a -> withIndex l (\i c -> if p i then f i c else pure c) a-{-# INLINE iwhereOf #-}---- | Traverse the value at a given key in a map------ @'traverseAt' k = 'at' k '<.' 'traverse'@-traverseAt :: At k m => k -> SimpleIndexedTraversal k (m v) v-traverseAt k = at k <. traverse-{-# INLINE traverseAt #-}---- | This provides a 'Traversal' that checks a predicate on a key before--- allowing you to traverse into a value.-value :: (k -> Bool) -> SimpleIndexedTraversal k (k, v) v-value p = index $ \ f kv@(k,v) -> if p k then (,) k <$> f k v else pure kv-{-# INLINE value #-}---- | Allows 'IndexedTraversal' the value at the smallest index.-class Ord k => TraverseMin k m | m -> k where-  -- | 'IndexedTraversal' of the element with the smallest index.-  traverseMin :: SimpleIndexedTraversal k (m v) v--instance TraverseMin Int IntMap where-  traverseMin = index $ \f m -> case IntMap.minViewWithKey m of-#if MIN_VERSION_containers(0,5,0)-    Just ((k,a), _) -> (\v -> IntMap.updateMin (const (Just v)) m) <$> f k a-#else-    Just ((k,a), _) -> (\v -> IntMap.updateMin (const v) m) <$> f k a-#endif-    Nothing     -> pure m-  {-# INLINE traverseMin #-}--instance Ord k => TraverseMin k (Map k) where-  traverseMin = index $ \f m -> case Map.minViewWithKey m of-    Just ((k, a), _) -> (\v -> Map.updateMin (const (Just v)) m) <$> f k a-    Nothing          -> pure m-  {-# INLINE traverseMin #-}---- | Allows 'IndexedTraversal' of the value at the largest index.-class Ord k => TraverseMax k m | m -> k where-  -- | 'IndexedTraversal' of the element at the largest index.-  traverseMax :: SimpleIndexedTraversal k (m v) v--instance TraverseMax Int IntMap where-  traverseMax = index $ \f m -> case IntMap.maxViewWithKey m of-#if MIN_VERSION_containers(0,5,0)-    Just ((k,a), _) -> (\v -> IntMap.updateMax (const (Just v)) m) <$> f k a-#else-    Just ((k,a), _) -> (\v -> IntMap.updateMax (const v) m) <$> f k a-#endif-    Nothing     -> pure m-  {-# INLINE traverseMax #-}--instance Ord k => TraverseMax k (Map k) where-  traverseMax = index $ \f m -> case Map.maxViewWithKey m of-    Just ((k, a), _) -> (\v -> Map.updateMax (const (Just v)) m) <$> f k a-    Nothing          -> pure m-  {-# INLINE traverseMax #-}----------------------------------------------------------------------------------- Reifying Indexed Traversals----------------------------------------------------------------------------------- | Useful for storage.-newtype ReifiedIndexedTraversal i a b c d = ReifyIndexedTraversal { reflectIndexedTraversal :: IndexedTraversal i a b c d }---- | @type 'SimpleIndexedTraversal' i = 'Simple' ('ReifiedIndexedTraversal' i)@-type SimpleReifiedIndexedTraversal i a b = ReifiedIndexedTraversal i a a b b
src/Control/Lens/Internal.hs view
@@ -1,488 +1,42 @@-{-# LANGUAGE Rank2Types #-}-{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE UndecidableInstances #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FunctionalDependencies #-} ----------------------------------------------------------------------------- -- | -- Module      :  Control.Lens.Internal--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional+-- Stability   :  experimental -- Portability :  Rank2Types ----- These are some of the explicit Functor instances that leak into the--- type signatures of Control.Lens. You shouldn't need to import this--- module directly, unless you are coming up with a whole new kind of--- \"Family\" and need to add instances.+-- These are some of the explicit 'Functor' instances that leak into the+-- type signatures of @Control.Lens@. You shouldn't need to import this+-- module directly for most use-cases. -- ---------------------------------------------------------------------------- module Control.Lens.Internal-  (-  -- * Implementation details-    Context(..)-  , Focusing(..)-  , FocusingWith(..)-  , FocusingPlus(..)-  , FocusingOn(..)-  , FocusingErr(..), Err(..)-  , FocusingMay(..), May(..)-  , Traversed(..)-  , Sequenced(..)-  , Indexing(..), IndexingResult(..)-  , Min(..)-  , getMin-  , Max(..)-  , getMax-  , ElementOf(..)-  , ElementOfResult(..)-  , Bazaar(..), bazaar, duplicateBazaar, sell-  , Effect(..)-  , EffectRWS(..)-  -- , EffectS(..)-  , Gettable(..), Accessor(..), Effective(..), ineffective, noEffect, Folding(..)-  , Settable(..), Mutator(..)+  ( module Control.Lens.Internal.Bazaar+  , module Control.Lens.Internal.Context+  , module Control.Lens.Internal.Fold+  , module Control.Lens.Internal.Getter+  , module Control.Lens.Internal.Indexed+  , module Control.Lens.Internal.Iso+  , module Control.Lens.Internal.Level+  , module Control.Lens.Internal.Magma+  , module Control.Lens.Internal.Prism+  , module Control.Lens.Internal.Review+  , module Control.Lens.Internal.Setter+  , module Control.Lens.Internal.Zoom   ) where -import Control.Applicative-import Control.Applicative.Backwards-import Control.Category-import Control.Comonad-import Control.Comonad.Store.Class-import Control.Lens.Isomorphic-import Control.Monad-import Prelude hiding ((.),id)-import Data.Functor.Compose-import Data.Functor.Identity-import Data.Monoid---------------------------------------------------------------------------------- Functors---------------------------------------------------------------------------------- | Used by 'Control.Lens.Type.Zoom' to 'Control.Lens.Type.zoom' into 'Control.Monad.State.StateT'-newtype Focusing m c a = Focusing { unfocusing :: m (c, a) }--instance Monad m => Functor (Focusing m c) where-  fmap f (Focusing m) = Focusing $ do-     (c, a) <- m-     return (c, f a)--instance (Monad m, Monoid c) => Applicative (Focusing m c) where-  pure a = Focusing (return (mempty, a))-  Focusing mf <*> Focusing ma = Focusing $ do-    (c, f) <- mf-    (d, a) <- ma-    return (mappend c d, f a)---- | Used by 'Control.Lens.Type.Zoom' to 'Control.Lens.Type.zoom' into 'Control.Monad.RWS.RWST'-newtype FocusingWith w m c a = FocusingWith { unfocusingWith :: m (c, a, w) }--instance Monad m => Functor (FocusingWith w m c) where-  fmap f (FocusingWith m) = FocusingWith $ do-     (c, a, w) <- m-     return (c, f a, w)--instance (Monad m, Monoid c, Monoid w) => Applicative (FocusingWith w m c) where-  pure a = FocusingWith (return (mempty, a, mempty))-  FocusingWith mf <*> FocusingWith ma = FocusingWith $ do-    (c, f, w) <- mf-    (d, a, w') <- ma-    return (mappend c d, f a, mappend w w')---- | Used by 'Control.Lens.Type.Zoom' to 'Control.Lens.Type.zoom' into 'Control.Monad.Writer.WriterT'.-newtype FocusingPlus w k c a = FocusingPlus { unfocusingPlus :: k (c, w) a }--instance Functor (k (c, w)) => Functor (FocusingPlus w k c) where-  fmap f (FocusingPlus as) = FocusingPlus (fmap f as)--instance (Monoid w, Applicative (k (c, w))) => Applicative (FocusingPlus w k c) where-  pure = FocusingPlus . pure-  FocusingPlus kf <*> FocusingPlus ka = FocusingPlus (kf <*> ka)---- | Used by 'Control.Lens.Type.Zoom' to 'Control.Lens.Type.zoom' into 'Control.Monad.Trans.Maybe.MaybeT' or 'Control.Monad.Trans.List.ListT'-newtype FocusingOn f k c a = FocusingOn { unfocusingOn :: k (f c) a }--instance Functor (k (f c)) => Functor (FocusingOn f k c) where-  fmap f (FocusingOn as) = FocusingOn (fmap f as)--instance Applicative (k (f c)) => Applicative (FocusingOn f k c) where-  pure = FocusingOn . pure-  FocusingOn kf <*> FocusingOn ka = FocusingOn (kf <*> ka)---- | Make a monoid out of 'Maybe' for error handling-newtype May a = May { getMay :: Maybe a }--instance Monoid a => Monoid (May a) where-  mempty = May (Just mempty)-  May Nothing `mappend` _ = May Nothing-  _ `mappend` May Nothing = May Nothing-  May (Just a) `mappend` May (Just b) = May (Just (mappend a b))---- | Used by 'Control.Lens.Type.Zoom' to 'Control.Lens.Type.zoom' into 'Control.Monad.Error.ErrorT'-newtype FocusingMay k c a = FocusingMay { unfocusingMay :: k (May c) a }--instance Functor (k (May c)) => Functor (FocusingMay k c) where-  fmap f (FocusingMay as) = FocusingMay (fmap f as)--instance Applicative (k (May c)) => Applicative (FocusingMay k c) where-  pure = FocusingMay . pure-  FocusingMay kf <*> FocusingMay ka = FocusingMay (kf <*> ka)---- | Make a monoid out of 'Either' for error handling-newtype Err e a = Err { getErr :: Either e a }--instance Monoid a => Monoid (Err e a) where-  mempty = Err (Right mempty)-  Err (Left e) `mappend` _ = Err (Left e)-  _ `mappend` Err (Left e) = Err (Left e)-  Err (Right a) `mappend` Err (Right b) = Err (Right (mappend a b))---- | Used by 'Control.Lens.Type.Zoom' to 'Control.Lens.Type.zoom' into 'Control.Monad.Error.ErrorT'-newtype FocusingErr e k c a = FocusingErr { unfocusingErr :: k (Err e c) a }--instance Functor (k (Err e c)) => Functor (FocusingErr e k c) where-  fmap f (FocusingErr as) = FocusingErr (fmap f as)--instance Applicative (k (Err e c)) => Applicative (FocusingErr e k c) where-  pure = FocusingErr . pure-  FocusingErr kf <*> FocusingErr ka = FocusingErr (kf <*> ka)---- | The indexed store can be used to characterize a 'Control.Lens.Type.Lens'--- and is used by 'Control.Lens.Type.clone'-data Context c d a = Context (d -> a) c--instance Functor (Context c d) where-  fmap f (Context g c) = Context (f . g) c--instance (c ~ d) => Comonad (Context c d) where-  extract   (Context f c) = f c-  duplicate (Context f c) = Context (Context f) c-  extend g  (Context f c) = Context (g . Context f) c--instance (c ~ d) => ComonadStore c (Context c d) where-  pos (Context _ c) = c-  peek c (Context g _) = g c-  peeks f (Context g c) = g (f c)-  seek c (Context g _) = Context g c-  seeks f (Context g c) = Context g (f c)-  experiment f (Context g c) = g <$> f c---- | The result of 'Indexing'-data IndexingResult f a = IndexingResult (f a) {-# UNPACK #-} !Int--instance Functor f => Functor (IndexingResult f) where-  fmap f (IndexingResult fa n) = IndexingResult (fmap f fa) n---- | Applicative composition of @'Control.Monad.Trans.State.Lazy.State' 'Int'@ with a 'Functor', used--- by 'Control.Lens.Indexed.indexed'-newtype Indexing f a = Indexing { runIndexing :: Int -> IndexingResult f a }--instance Functor f => Functor (Indexing f) where-  fmap f (Indexing m) = Indexing $ \i -> fmap f (m i)--instance Applicative f => Applicative (Indexing f) where-  pure = Indexing . IndexingResult . pure-  Indexing mf <*> Indexing ma = Indexing $ \i -> case mf i of-    IndexingResult ff j -> case ma j of-       IndexingResult fa k -> IndexingResult (ff <*> fa) k--instance Gettable f => Gettable (Indexing f) where-  coerce (Indexing m) = Indexing $ \i -> case m i of-    IndexingResult ff j -> IndexingResult (coerce ff) j---- | Used internally by 'Control.Lens.Traversal.traverseOf_' and the like.-newtype Traversed f = Traversed { getTraversed :: f () }--instance Applicative f => Monoid (Traversed f) where-  mempty = Traversed (pure ())-  Traversed ma `mappend` Traversed mb = Traversed (ma *> mb)---- | Used internally by 'Control.Lens.Traversal.mapM_' and the like.-newtype Sequenced m = Sequenced { getSequenced :: m () }--instance Monad m => Monoid (Sequenced m) where-  mempty = Sequenced (return ())-  Sequenced ma `mappend` Sequenced mb = Sequenced (ma >> mb)---- | Used for 'Control.Lens.Fold.minimumOf'-data Min a = NoMin | Min a--instance Ord a => Monoid (Min a) where-  mempty = NoMin-  mappend NoMin m = m-  mappend m NoMin = m-  mappend (Min a) (Min b) = Min (min a b)---- | Obtain the minimum.-getMin :: Min a -> Maybe a-getMin NoMin   = Nothing-getMin (Min a) = Just a---- | Used for 'Control.Lens.Fold.maximumOf'-data Max a = NoMax | Max a--instance Ord a => Monoid (Max a) where-  mempty = NoMax-  mappend NoMax m = m-  mappend m NoMax = m-  mappend (Max a) (Max b) = Max (max a b)---- | Obtain the maximum-getMax :: Max a -> Maybe a-getMax NoMax   = Nothing-getMax (Max a) = Just a---- | The result of trying to find the /n/th 'Control.Lens.Traversal.element' of a 'Control.Lens.Traversal.Traversal'.-data ElementOfResult f a-  = Searching {-# UNPACK #-} !Int a-  | Found {-# UNPACK #-} !Int (f a)-  | NotFound String--instance Functor f => Functor (ElementOfResult f) where-  fmap f (Searching i a) = Searching i (f a)-  fmap f (Found i as) = Found i (fmap f as)-  fmap _ (NotFound e) = NotFound e---- | Used to find the /n/th 'Control.Lens.Traversal.element' of a 'Control.Lens.Traversal.Traversal'.-newtype ElementOf f a = ElementOf { getElementOf :: Int -> ElementOfResult f a }--instance Functor f => Functor (ElementOf f) where-  fmap f (ElementOf m) = ElementOf $ \i -> case m i of-    Searching j a -> Searching j (f a)-    Found j as    -> Found j (fmap f as)-    NotFound e    -> NotFound e--instance Functor f => Applicative (ElementOf f) where-  pure a = ElementOf $ \i -> Searching i a-  ElementOf mf <*> ElementOf ma = ElementOf $ \i -> case mf i of-    Found j ff -> case ma j of-      Found _ _     -> NotFound "multiple results"-      Searching k a -> Found k (fmap ($ a) ff)-      NotFound e    -> NotFound e-    Searching j f -> case ma j of-      Found k as    -> Found k (fmap f as)-      Searching k a -> Searching k (f a)-      NotFound e    -> NotFound e-    NotFound e -> NotFound e----- | This is used to characterize a 'Control.Lens.Traversal.Traversal'.------ a.k.a. indexed Cartesian store comonad, indexed Kleene store comonad, or an indexed 'FunList'.------ <http://twanvl.nl/blog/haskell/non-regular1>------ Mnemonically, a 'Bazaar' holds many stores and you can easily add more.------ This is a final encoding of 'Bazaar'.-newtype Bazaar c d a = Bazaar { _runBazaar :: forall f. Applicative f => (c -> f d) -> f a }--instance Functor (Bazaar c d) where-  fmap f (Bazaar k) = Bazaar (fmap f . k)--instance Applicative (Bazaar c d) where-  pure a = Bazaar (\_ -> pure a)-  {-# INLINE pure #-}-  Bazaar mf <*> Bazaar ma = Bazaar (\k -> mf k <*> ma k)-  {-# INLINE (<*>) #-}--instance (c ~ d) => Comonad (Bazaar c d) where-  extract (Bazaar m) = runIdentity (m Identity)-  {-# INLINE extract #-}-  duplicate = duplicateBazaar-  {-# INLINE duplicate #-}---- | Given an action to run for each matched pair, traverse a bazaar.-bazaar :: Applicative f => (c -> f d) -> Bazaar c d b -> f b-bazaar cfd (Bazaar m) = m cfd-{-# INLINE bazaar #-}---- | 'Bazaar' is an indexed 'Comonad'.-duplicateBazaar :: Bazaar c e a -> Bazaar c d (Bazaar d e a)-duplicateBazaar (Bazaar m) = getCompose (m (Compose . fmap sell . sell))-{-# INLINE duplicateBazaar #-}--- duplicateBazaar' (Bazaar m) = Bazaar (\g -> getCompose (m (Compose . fmap sell . g)))---- | A trivial 'Bazaar'.-sell :: c -> Bazaar c d d-sell i = Bazaar (\k -> k i)-{-# INLINE sell #-}--instance (c ~ d) => ComonadApply (Bazaar c d) where-  (<@>) = (<*>)---- | Wrap a monadic effect with a phantom type argument.-newtype Effect m r a = Effect { getEffect :: m r }--instance Functor (Effect m r) where-  fmap _ (Effect m) = Effect m--instance (Monad m, Monoid r) => Monoid (Effect m r a) where-  mempty = Effect (return mempty)-  Effect ma `mappend` Effect mb = Effect (liftM2 mappend ma mb)--instance (Monad m, Monoid r) => Applicative (Effect m r) where-  pure _ = Effect (return mempty)-  Effect ma <*> Effect mb = Effect (liftM2 mappend ma mb)---- | Wrap a monadic effect with a phantom type argument. Used when magnifying RWST.-newtype EffectRWS w s m c a = EffectRWS { getEffectRWS :: s -> m (c,s,w) }--instance Functor (EffectRWS w s m c) where-  fmap _ (EffectRWS m) = EffectRWS m--instance (Monoid c, Monoid w, Monad m) => Applicative (EffectRWS w s m c) where-  pure _ = EffectRWS $ \s -> return (mempty, s, mempty)-  EffectRWS m <*> EffectRWS n = EffectRWS $ \s -> m s >>= \ (c,t,w) -> n t >>= \ (c',u,w') -> return (mappend c c', u, mappend w w')--{---- | Wrap a monadic effect with a phantom type argument. Used when magnifying StateT.-newtype EffectS s k c a = EffectS { runEffect :: s -> k (c, s) a }--instance Functor (k (c, s)) => Functor (EffectS s m c) where-  fmap f (EffectS m) = EffectS (fmap f . m)--instance (Monoid c, Monad m) => Applicative (EffectS s m c) where-  pure _ = EffectS $ \s -> return (mempty, s)-  EffectS m <*> EffectS n = EffectS $ \s -> m s >>= \ (c,t) -> n s >>= \ (d, u) -> return (mappend c d, u)--}------------------------------------------------------------------------------------ Gettables & Accessors------------------------------------------------------------------------------------ | Generalizing 'Const' so we can apply simple 'Applicative'--- transformations to it and so we can get nicer error messages------ A 'Gettable' 'Functor' ignores its argument, which it carries solely as a--- phantom type parameter.------ To ensure this, an instance of 'Gettable' is required to satisfy:------ @'id' = 'fmap' f = 'coerce'@-class Functor f => Gettable f where-  -- | Replace the phantom type argument.-  coerce :: f a -> f b--instance Gettable (Const r) where-  coerce (Const m) = Const m--instance Gettable f => Gettable (Backwards f) where-  coerce = Backwards . coerce . forwards--instance (Functor f, Gettable g) => Gettable (Compose f g) where-  coerce = Compose . fmap coerce . getCompose--instance Gettable (Effect m r) where-  coerce (Effect m) = Effect m--instance Gettable (EffectRWS w s m c) where-  coerce (EffectRWS m) = EffectRWS m----instance Gettable (EffectS s m c) where---  coerce (EffectS m) = EffectS m---- | This instance is a lie, but it is a useful lie.-instance Gettable f => Gettable (ElementOf f) where-  coerce (ElementOf m) = ElementOf $ \i -> case m i of-    Searching _ _ -> NotFound "coerced while searching" -- er...-    Found j as    -> Found j (coerce as)-    NotFound s    -> NotFound s--instance Gettable (Accessor r) where-  coerce (Accessor m) = Accessor m---- | Used instead of 'Const' to report------ @No instance of ('Control.Lens.Setter.Settable' 'Accessor')@------ when the user attempts to misuse a 'Control.Lens.Setter.Setter' as a--- 'Control.Lens.Getter.Getter', rather than a monolithic unification error.-newtype Accessor r a = Accessor { runAccessor :: r }--instance Functor (Accessor r) where-  fmap _ (Accessor m) = Accessor m--instance Monoid r => Applicative (Accessor r) where-  pure _ = Accessor mempty-  Accessor a <*> Accessor b = Accessor (mappend a b)---- | An 'Effective' 'Functor' ignores its argument and is isomorphic to a monad wrapped around a value.------ That said, the monad is possibly rather unrelated to any 'Applicative' structure.-class (Monad m, Gettable f) => Effective m r f | f -> m r where-  effective :: Isomorphic k => k (m r) (f a)---- | A convenient antonym that is used internally.-ineffective :: Effective m r f => Isomorphic k => k (f a) (m r)-ineffective = from effective-{-# INLINE ineffective #-}--instance Effective Identity r (Accessor r) where-  effective = isomorphic (Accessor . runIdentity) (Identity . runAccessor)-  {-# INLINE effective #-}--instance Effective m r f => Effective m (Dual r) (Backwards f) where-  effective = isomorphic (Backwards . effective . liftM getDual) (liftM Dual . ineffective . forwards)--instance Monad m => Effective m r (Effect m r) where-  effective = isomorphic Effect getEffect-  {-# INLINE effective #-}---- | A 'Monoid' for a 'Gettable' 'Applicative'.-newtype Folding f a = Folding { getFolding :: f a }--instance (Gettable f, Applicative f) => Monoid (Folding f a) where-  mempty = Folding noEffect-  {-# INLINE mempty #-}-  Folding fr `mappend` Folding fs = Folding (fr *> fs)-  {-# INLINE mappend #-}---- | The 'mempty' equivalent for a 'Gettable' 'Applicative' 'Functor'.-noEffect :: (Applicative f, Gettable f) => f a-noEffect = coerce $ pure ()-{-# INLINE noEffect #-}---------------------------------------------------------------------------------- Settables & Mutators---------------------------------------------------------------------------------- | Anything 'Settable' must be isomorphic to the 'Identity' 'Functor'.-class Applicative f => Settable f where-  untainted :: f a -> a---- | so you can pass our a 'Control.Lens.Setter.Setter' into combinators from other lens libraries-instance Settable Identity where-  untainted = runIdentity-  {-# INLINE untainted #-}---- | 'Control.Lens.Fold.backwards'-instance Settable f => Settable (Backwards f) where-  untainted = untainted . forwards-  {-# INLINE untainted #-}--instance (Settable f, Settable g) => Settable (Compose f g) where-  untainted = untainted . untainted . getCompose-  {-# INLINE untainted #-}--instance Settable Mutator where-  untainted = runMutator-  {-# INLINE untainted #-}---- | 'Mutator' is just a renamed 'Identity' functor to give better error--- messages when someone attempts to use a getter as a setter.------ Most user code will never need to see this type.-newtype Mutator a = Mutator { runMutator :: a }--instance Functor Mutator where-  fmap f (Mutator a) = Mutator (f a)--instance Applicative Mutator where-  pure = Mutator-  Mutator f <*> Mutator a = Mutator (f a)-+import Control.Lens.Internal.Bazaar+import Control.Lens.Internal.Context+import Control.Lens.Internal.Fold+import Control.Lens.Internal.Getter+import Control.Lens.Internal.Indexed+import Control.Lens.Internal.Instances ()+import Control.Lens.Internal.Iso+import Control.Lens.Internal.Level+import Control.Lens.Internal.Magma+import Control.Lens.Internal.Prism+import Control.Lens.Internal.Review+import Control.Lens.Internal.Setter+import Control.Lens.Internal.Zoom
+ src/Control/Lens/Internal/Bazaar.hs view
@@ -0,0 +1,388 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE RoleAnnotations #-}+{-# OPTIONS_GHC -Wno-redundant-constraints #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Bazaar+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+----------------------------------------------------------------------------+module Control.Lens.Internal.Bazaar+  ( Bizarre(..)+  , Bazaar(..), Bazaar'+  , BazaarT(..), BazaarT'+  , Bizarre1(..)+  , Bazaar1(..), Bazaar1'+  , BazaarT1(..), BazaarT1'+  ) where++import Prelude ()++import Control.Arrow as Arrow+import qualified Control.Category as C+import Control.Comonad+import Control.Lens.Internal.Prelude+import Control.Lens.Internal.Context+import Control.Lens.Internal.Indexed+import Data.Functor.Apply+import Data.Kind+import Data.Profunctor.Rep++------------------------------------------------------------------------------+-- Bizarre+------------------------------------------------------------------------------++-- | This class is used to run the various 'Bazaar' variants used in this+-- library.+class Profunctor p => Bizarre p w | w -> p where+  bazaar :: Applicative f => p a (f b) -> w a b t -> f t++------------------------------------------------------------------------------+-- Bazaar+------------------------------------------------------------------------------++-- | This is used to characterize a 'Control.Lens.Traversal.Traversal'.+--+-- a.k.a. indexed Cartesian store comonad, indexed Kleene store comonad, or an indexed 'FunList'.+--+-- <http://twanvl.nl/blog/haskell/non-regular1>+--+-- A 'Bazaar' is like a 'Control.Lens.Traversal.Traversal' that has already been applied to some structure.+--+-- Where a @'Context' a b t@ holds an @a@ and a function from @b@ to+-- @t@, a @'Bazaar' a b t@ holds @N@ @a@s and a function from @N@+-- @b@s to @t@, (where @N@ might be infinite).+--+-- Mnemonically, a 'Bazaar' holds many stores and you can easily add more.+--+-- This is a final encoding of 'Bazaar'.+newtype Bazaar p a b t = Bazaar { runBazaar :: forall f. Applicative f => p a (f b) -> f t }+-- type role Bazaar representatonal nominal nominal nominal++-- | This alias is helpful when it comes to reducing repetition in type signatures.+--+-- @+-- type 'Bazaar'' p a t = 'Bazaar' p a a t+-- @+type Bazaar' p a = Bazaar p a a++instance IndexedFunctor (Bazaar p) where+  ifmap f (Bazaar k) = Bazaar (fmap f . k)+  {-# INLINE ifmap #-}++instance Conjoined p => IndexedComonad (Bazaar p) where+  iextract (Bazaar m) = runIdentity $ m (arr Identity)+  {-# INLINE iextract #-}+  iduplicate (Bazaar m) = getCompose $ m (Compose #. distrib sell C.. sell)+  {-# INLINE iduplicate #-}++instance Corepresentable p => Sellable p (Bazaar p) where+  sell = cotabulate $ \ w -> Bazaar $ tabulate $ \k -> pure (cosieve k w)+  {-# INLINE sell #-}++instance Profunctor p => Bizarre p (Bazaar p) where+  bazaar g (Bazaar f) = f g+  {-# INLINE bazaar #-}++instance Functor (Bazaar p a b) where+  fmap = ifmap+  {-# INLINE fmap #-}+  x <$ Bazaar k = Bazaar ( (x <$) . k )+  {-# INLINE (<$) #-}++instance Apply (Bazaar p a b) where+  (<.>) = (<*>)+  {-# INLINE (<.>) #-}+  (.>) = (*>)+  {-# INLINE (.>) #-}+  (<.) = (<*)+  {-# INLINE (<.) #-}++instance Applicative (Bazaar p a b) where+  pure a = Bazaar $ \_ -> pure a+  {-# INLINE pure #-}+  Bazaar mf <*> Bazaar ma = Bazaar $ \ pafb -> mf pafb <*> ma pafb+  {-# INLINE (<*>) #-}+#if MIN_VERSION_base(4,10,0)+  liftA2 f (Bazaar mx) (Bazaar my) = Bazaar $ \pafb -> liftA2 f (mx pafb) (my pafb)+  {-# INLINE liftA2 #-}+#endif+  Bazaar mx *> Bazaar my = Bazaar $ \pafb -> mx pafb *> my pafb+  {-# INLINE (*>) #-}+  Bazaar mx <* Bazaar my = Bazaar $ \pafb -> mx pafb <* my pafb+  {-# INLINE (<*) #-}++instance (a ~ b, Conjoined p) => Comonad (Bazaar p a b) where+  extract = iextract+  {-# INLINE extract #-}+  duplicate = iduplicate+  {-# INLINE duplicate #-}++instance (a ~ b, Conjoined p) => ComonadApply (Bazaar p a b) where+  (<@>) = (<*>)+  {-# INLINE (<@>) #-}+  (@>) = (*>)+  {-# INLINE (@>) #-}+  (<@) = (<*)+  {-# INLINE (<@) #-}++------------------------------------------------------------------------------+-- BazaarT+------------------------------------------------------------------------------++-- | 'BazaarT' is like 'Bazaar', except that it provides a questionable 'Contravariant' instance+-- To protect this instance it relies on the soundness of another 'Contravariant' type, and usage conventions.+--+-- For example. This lets us write a suitably polymorphic and lazy 'Control.Lens.Traversal.taking', but there+-- must be a better way!+newtype BazaarT p (g :: Type -> Type) a b t = BazaarT { runBazaarT :: forall f. Applicative f => p a (f b) -> f t }+type role BazaarT representational nominal nominal nominal nominal++-- | This alias is helpful when it comes to reducing repetition in type signatures.+--+-- @+-- type 'BazaarT'' p g a t = 'BazaarT' p g a a t+-- @+type BazaarT' p g a = BazaarT p g a a++instance IndexedFunctor (BazaarT p g) where+  ifmap f (BazaarT k) = BazaarT (fmap f . k)+  {-# INLINE ifmap #-}++instance Conjoined p => IndexedComonad (BazaarT p g) where+  iextract (BazaarT m) = runIdentity $ m (arr Identity)+  {-# INLINE iextract #-}+  iduplicate (BazaarT m) = getCompose $ m (Compose #. distrib sell C.. sell)+  {-# INLINE iduplicate #-}++instance Corepresentable p => Sellable p (BazaarT p g) where+  sell = cotabulate $ \ w -> BazaarT (`cosieve` w)+  {-# INLINE sell #-}++instance Profunctor p => Bizarre p (BazaarT p g) where+  bazaar g (BazaarT f) = f g+  {-# INLINE bazaar #-}++instance Functor (BazaarT p g a b) where+  fmap = ifmap+  {-# INLINE fmap #-}+  x <$ BazaarT k = BazaarT ( (x <$) . k )+  {-# INLINE (<$) #-}++instance Apply (BazaarT p g a b) where+  (<.>) = (<*>)+  {-# INLINE (<.>) #-}+  (.>) = (*>)+  {-# INLINE (.>) #-}+  (<.) = (<*)+  {-# INLINE (<.) #-}++instance Applicative (BazaarT p g a b) where+  pure a = BazaarT $ tabulate $ \_ -> pure (pure a)+  {-# INLINE pure #-}+  BazaarT mf <*> BazaarT ma = BazaarT $ \ pafb -> mf pafb <*> ma pafb+  {-# INLINE (<*>) #-}+#if MIN_VERSION_base(4,10,0)+  liftA2 f (BazaarT mx) (BazaarT my) = BazaarT $ \pafb -> liftA2 f (mx pafb) (my pafb)+  {-# INLINE liftA2 #-}+#endif+  BazaarT mf *> BazaarT ma = BazaarT $ \ pafb -> mf pafb *> ma pafb+  {-# INLINE (*>) #-}+  BazaarT mf <* BazaarT ma = BazaarT $ \ pafb -> mf pafb <* ma pafb+  {-# INLINE (<*) #-}++instance (a ~ b, Conjoined p) => Comonad (BazaarT p g a b) where+  extract = iextract+  {-# INLINE extract #-}+  duplicate = iduplicate+  {-# INLINE duplicate #-}++instance (a ~ b, Conjoined p) => ComonadApply (BazaarT p g a b) where+  (<@>) = (<*>)+  {-# INLINE (<@>) #-}+  (@>) = (*>)+  {-# INLINE (@>) #-}+  (<@) = (<*)+  {-# INLINE (<@) #-}++instance (Profunctor p, Contravariant g) => Contravariant (BazaarT p g a b) where+  contramap _ = (<$) (error "contramap: BazaarT")+  {-# INLINE contramap #-}++instance Contravariant g => Semigroup (BazaarT p g a b t) where+  BazaarT a <> BazaarT b = BazaarT $ \f -> a f <* b f+  {-# INLINE (<>) #-}++instance Contravariant g => Monoid (BazaarT p g a b t) where+  mempty = BazaarT $ \_ -> pure (error "mempty: BazaarT")+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  BazaarT a `mappend` BazaarT b = BazaarT $ \f -> a f <* b f+  {-# INLINE mappend #-}+#endif+++------------------------------------------------------------------------------+-- Bizarre1+------------------------------------------------------------------------------++class Profunctor p => Bizarre1 p w | w -> p where+  bazaar1 :: Apply f => p a (f b) -> w a b t -> f t++------------------------------------------------------------------------------+-- Bazaar1+------------------------------------------------------------------------------++-- | This is used to characterize a 'Control.Lens.Traversal.Traversal'.+--+-- a.k.a. indexed Cartesian store comonad, indexed Kleene store comonad, or an indexed 'FunList'.+--+-- <http://twanvl.nl/blog/haskell/non-regular1>+--+-- A 'Bazaar1' is like a 'Control.Lens.Traversal.Traversal' that has already been applied to some structure.+--+-- Where a @'Context' a b t@ holds an @a@ and a function from @b@ to+-- @t@, a @'Bazaar1' a b t@ holds @N@ @a@s and a function from @N@+-- @b@s to @t@, (where @N@ might be infinite).+--+-- Mnemonically, a 'Bazaar1' holds many stores and you can easily add more.+--+-- This is a final encoding of 'Bazaar1'.+newtype Bazaar1 p a b t = Bazaar1 { runBazaar1 :: forall f. Apply f => p a (f b) -> f t }+-- type role Bazaar1 representatonal nominal nominal nominal++-- | This alias is helpful when it comes to reducing repetition in type signatures.+--+-- @+-- type 'Bazaar1'' p a t = 'Bazaar1' p a a t+-- @+type Bazaar1' p a = Bazaar1 p a a++instance IndexedFunctor (Bazaar1 p) where+  ifmap f (Bazaar1 k) = Bazaar1 (fmap f . k)+  {-# INLINE ifmap #-}++instance Conjoined p => IndexedComonad (Bazaar1 p) where+  iextract (Bazaar1 m) = runIdentity $ m (arr Identity)+  {-# INLINE iextract #-}+  iduplicate (Bazaar1 m) = getCompose $ m (Compose #. distrib sell C.. sell)+  {-# INLINE iduplicate #-}++instance Corepresentable p => Sellable p (Bazaar1 p) where+  sell = cotabulate $ \ w -> Bazaar1 $ tabulate $ \k -> pure (cosieve k w)+  {-# INLINE sell #-}++instance Profunctor p => Bizarre1 p (Bazaar1 p) where+  bazaar1 g (Bazaar1 f) = f g+  {-# INLINE bazaar1 #-}++instance Functor (Bazaar1 p a b) where+  fmap = ifmap+  {-# INLINE fmap #-}+  x <$ Bazaar1 k = Bazaar1 ((x <$) . k)+  {-# INLINE (<$) #-}++instance Apply (Bazaar1 p a b) where+  Bazaar1 mf <.> Bazaar1 ma = Bazaar1 $ \ pafb -> mf pafb <.> ma pafb+  {-# INLINE (<.>) #-}+  Bazaar1 mf .> Bazaar1 ma = Bazaar1 $ \ pafb -> mf pafb .> ma pafb+  {-# INLINE (.>) #-}+  Bazaar1 mf <. Bazaar1 ma = Bazaar1 $ \ pafb -> mf pafb <. ma pafb+  {-# INLINE (<.) #-}++instance (a ~ b, Conjoined p) => Comonad (Bazaar1 p a b) where+  extract = iextract+  {-# INLINE extract #-}+  duplicate = iduplicate+  {-# INLINE duplicate #-}++instance (a ~ b, Conjoined p) => ComonadApply (Bazaar1 p a b) where+  (<@>) = (<.>)+  {-# INLINE (<@>) #-}+  (@>) = (.>)+  {-# INLINE (@>) #-}+  (<@) = (<.)+  {-# INLINE (<@) #-}++------------------------------------------------------------------------------+-- BazaarT1+------------------------------------------------------------------------------++-- | 'BazaarT1' is like 'Bazaar1', except that it provides a questionable 'Contravariant' instance+-- To protect this instance it relies on the soundness of another 'Contravariant' type, and usage conventions.+--+-- For example. This lets us write a suitably polymorphic and lazy 'Control.Lens.Traversal.taking', but there+-- must be a better way!+newtype BazaarT1 p (g :: Type -> Type) a b t = BazaarT1 { runBazaarT1 :: forall f. Apply f => p a (f b) -> f t }+type role BazaarT1 representational nominal nominal nominal nominal++-- | This alias is helpful when it comes to reducing repetition in type signatures.+--+-- @+-- type 'BazaarT1'' p g a t = 'BazaarT1' p g a a t+-- @+type BazaarT1' p g a = BazaarT1 p g a a++instance IndexedFunctor (BazaarT1 p g) where+  ifmap f (BazaarT1 k) = BazaarT1 (fmap f . k)+  {-# INLINE ifmap #-}++instance Conjoined p => IndexedComonad (BazaarT1 p g) where+  iextract (BazaarT1 m) = runIdentity $ m (arr Identity)+  {-# INLINE iextract #-}+  iduplicate (BazaarT1 m) = getCompose $ m (Compose #. distrib sell C.. sell)+  {-# INLINE iduplicate #-}++instance Corepresentable p => Sellable p (BazaarT1 p g) where+  sell = cotabulate $ \ w -> BazaarT1 (`cosieve` w)+  {-# INLINE sell #-}++instance Profunctor p => Bizarre1 p (BazaarT1 p g) where+  bazaar1 g (BazaarT1 f) = f g+  {-# INLINE bazaar1 #-}++instance Functor (BazaarT1 p g a b) where+  fmap = ifmap+  {-# INLINE fmap #-}+  x <$ BazaarT1 k = BazaarT1 ((x <$) . k)+  {-# INLINE (<$) #-}++instance Apply (BazaarT1 p g a b) where+  BazaarT1 mf <.> BazaarT1 ma = BazaarT1 $ \ pafb -> mf pafb <.> ma pafb+  {-# INLINE (<.>) #-}+  BazaarT1 mf .> BazaarT1 ma = BazaarT1 $ \ pafb -> mf pafb .> ma pafb+  {-# INLINE (.>) #-}+  BazaarT1 mf <. BazaarT1 ma = BazaarT1 $ \ pafb -> mf pafb <. ma pafb+  {-# INLINE (<.) #-}++instance (a ~ b, Conjoined p) => Comonad (BazaarT1 p g a b) where+  extract = iextract+  {-# INLINE extract #-}+  duplicate = iduplicate+  {-# INLINE duplicate #-}++instance (a ~ b, Conjoined p) => ComonadApply (BazaarT1 p g a b) where+  (<@>) = (<.>)+  {-# INLINE (<@>) #-}+  (@>) = (.>)+  {-# INLINE (@>) #-}+  (<@) = (<.)+  {-# INLINE (<@) #-}++instance (Profunctor p, Contravariant g) => Contravariant (BazaarT1 p g a b) where+  contramap _ = (<$) (error "contramap: BazaarT1")+  {-# INLINE contramap #-}++instance Contravariant g => Semigroup (BazaarT1 p g a b t) where+  BazaarT1 a <> BazaarT1 b = BazaarT1 $ \f -> a f <. b f+  {-# INLINE (<>) #-}
+ src/Control/Lens/Internal/ByteString.hs view
@@ -0,0 +1,218 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE PatternGuards #-}+{-# LANGUAGE FlexibleContexts #-}+#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-}+#endif++#include "lens-common.h"++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.ByteString.Strict.Lens+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-- This module spends a lot of time fiddling around with 'Data.ByteString' internals+-- to work around <http://hackage.haskell.org/trac/ghc/ticket/7556> on older+-- Haskell Platforms and to improve constant and asymptotic factors in our performance.+----------------------------------------------------------------------------+module Control.Lens.Internal.ByteString+  ( traversedStrictTree, traversedStrictTree8+  , traversedLazy, traversedLazy8+  ) where++import Prelude ()++import Control.Lens.Type+import Control.Lens.Getter+import Control.Lens.Fold+import Control.Lens.Indexed+import Control.Lens.Internal.Prelude+import Control.Lens.Setter+import qualified Data.ByteString               as B+import qualified Data.ByteString.Char8         as B8+import qualified Data.ByteString.Lazy          as BL+import qualified Data.ByteString.Lazy.Char8    as BL8+import qualified Data.ByteString.Internal      as BI+import qualified Data.ByteString.Unsafe        as BU+import Data.Bits+import Data.Char+import Data.Int (Int64)+import Data.Word (Word8)+import Foreign.Ptr+import Foreign.Storable+import Foreign.ForeignPtr+import GHC.Base (unsafeChr)+import GHC.ForeignPtr (mallocPlainForeignPtrBytes)+import GHC.IO (unsafeDupablePerformIO)++grain :: Int+grain = 32+{-# INLINE grain #-}++-- | Traverse a strict 'B.ByteString' in a relatively balanced fashion, as a balanced tree with biased runs of+-- elements at the leaves.+traversedStrictTree :: IndexedTraversal' Int B.ByteString Word8+traversedStrictTree pafb bs = unsafeCreate len <$> go 0 len+ where+   len = B.length bs+   go !i !j+     | i + grain < j, k <- i + shiftR (j - i) 1 = (\l r q -> l q >> r q) <$> go i k <*> go k j+     | otherwise = run i j+   run !i !j+     | i == j    = pure (\_ -> return ())+     | otherwise = let !x = BU.unsafeIndex bs i+                   in (\y ys q -> pokeByteOff q i y >> ys q) <$> indexed pafb (i :: Int) x <*> run (i + 1) j+{-# INLINE [0] traversedStrictTree #-}++{-# RULES+"bytes -> map"    traversedStrictTree = sets B.map        :: ASetter' B.ByteString Word8;+"bytes -> imap"   traversedStrictTree = isets imapB       :: AnIndexedSetter' Int B.ByteString Word8;+"bytes -> foldr"  traversedStrictTree = foldring B.foldr  :: Getting (Endo r) B.ByteString Word8;+"bytes -> ifoldr" traversedStrictTree = ifoldring ifoldrB :: IndexedGetting Int (Endo r) B.ByteString Word8;+ #-}++imapB :: (Int -> Word8 -> Word8) -> B.ByteString -> B.ByteString+imapB f = snd . B.mapAccumL (\i a -> i `seq` (i + 1, f i a)) 0+{-# INLINE imapB #-}++ifoldrB :: (Int -> Word8 -> a -> a) -> a -> B.ByteString -> a+ifoldrB f z xs = B.foldr (\ x g i -> i `seq` f i x (g (i+1))) (const z) xs 0+{-# INLINE ifoldrB #-}++-- | Traverse a strict 'B.ByteString' in a relatively balanced fashion, as a balanced tree with biased runs of+-- elements at the leaves, pretending the bytes are chars.+traversedStrictTree8 :: IndexedTraversal' Int B.ByteString Char+traversedStrictTree8 pafb bs = unsafeCreate len <$> go 0 len+ where+   len = B.length bs+   go !i !j+     | i + grain < j    = let k = i + shiftR (j - i) 1+                          in (\l r q -> l q >> r q) <$> go i k <*> go k j+     | otherwise        = run i j+   run !i !j+     | i == j           = pure (\_ -> return ())+     | otherwise        = let !x = BU.unsafeIndex bs i+                          in (\y ys q -> pokeByteOff q i (c2w y) >> ys q)+                         <$> indexed pafb (i :: Int) (w2c x)+                         <*> run (i + 1) j+{-# INLINE [0] traversedStrictTree8 #-}++{-# RULES+"chars -> map"    traversedStrictTree8 = sets B8.map        :: ASetter' B.ByteString Char;+"chars -> imap"   traversedStrictTree8 = isets imapB8       :: AnIndexedSetter' Int B.ByteString Char;+"chars -> foldr"  traversedStrictTree8 = foldring B8.foldr  :: Getting (Endo r) B.ByteString Char;+"chars -> ifoldr" traversedStrictTree8 = ifoldring ifoldrB8 :: IndexedGetting Int (Endo r) B.ByteString Char;+ #-}++imapB8 :: (Int -> Char -> Char) -> B.ByteString -> B.ByteString+imapB8 f = snd . B8.mapAccumL (\i a -> i `seq` (i + 1, f i a)) 0+{-# INLINE imapB8 #-}++ifoldrB8 :: (Int -> Char -> a -> a) -> a -> B.ByteString -> a+ifoldrB8 f z xs = B8.foldr (\ x g i -> i `seq` f i x (g (i+1))) (const z) xs 0+{-# INLINE ifoldrB8 #-}++-- | An 'IndexedTraversal' of the individual bytes in a lazy 'BL.ByteString'+traversedLazy :: IndexedTraversal' Int64 BL.ByteString Word8+traversedLazy pafb = \lbs -> BL.foldrChunks go (\_ -> pure BL.empty) lbs 0+  where+  go c fcs acc = BL.append . BL.fromStrict+             <$> reindexed (\x -> acc + fromIntegral x :: Int64) traversedStrictTree pafb c+             <*> fcs acc'+    where+    acc' :: Int64+    !acc' = acc + fromIntegral (B.length c)+{-# INLINE [1] traversedLazy #-}++{-# RULES+  "sets lazy bytestring"+    traversedLazy = sets BL.map :: ASetter' BL.ByteString Word8;+  "isets lazy bytestring"+    traversedLazy = isets imapBL :: AnIndexedSetter' Int BL.ByteString Word8;+  "gets lazy bytestring"+    traversedLazy = foldring BL.foldr :: Getting (Endo r) BL.ByteString Word8;+  "igets lazy bytestring"+    traversedLazy = ifoldring ifoldrBL :: IndexedGetting Int (Endo r) BL.ByteString Word8;+ #-}++imapBL :: (Int -> Word8 -> Word8) -> BL.ByteString -> BL.ByteString+imapBL f = snd . BL.mapAccumL (\i a -> i `seq` (i + 1, f i a)) 0+{-# INLINE imapBL #-}++ifoldrBL :: (Int -> Word8 -> a -> a) -> a -> BL.ByteString -> a+ifoldrBL f z xs = BL.foldr (\ x g i -> i `seq` f i x (g (i+1))) (const z) xs 0+{-# INLINE ifoldrBL #-}++-- | An 'IndexedTraversal' of the individual bytes in a lazy 'BL.ByteString' pretending the bytes are chars.+traversedLazy8 :: IndexedTraversal' Int64 BL.ByteString Char+traversedLazy8 pafb = \lbs -> BL.foldrChunks go (\_ -> pure BL.empty) lbs 0+  where+  go c fcs acc = BL.append . BL.fromStrict+             <$> reindexed (\x -> acc + fromIntegral x :: Int64) traversedStrictTree8 pafb c+             <*> fcs acc'+    where+    acc' :: Int64+    !acc' = acc + fromIntegral (B.length c)+{-# INLINE [1] traversedLazy8 #-}++{-# RULES+  "sets lazy bytestring"+    traversedLazy8 = sets BL8.map :: ASetter' BL8.ByteString Char;+  "isets lazy bytestring"+    traversedLazy8 = isets imapBL8 :: AnIndexedSetter' Int BL8.ByteString Char;+  "gets lazy bytestring"+    traversedLazy8 = foldring BL8.foldr :: Getting (Endo r) BL8.ByteString Char;+  "igets lazy bytestring"+    traversedLazy8 = ifoldring ifoldrBL8 :: IndexedGetting Int (Endo r) BL8.ByteString Char;+ #-}++imapBL8 :: (Int -> Char -> Char) -> BL8.ByteString -> BL8.ByteString+imapBL8 f = snd . BL8.mapAccumL (\i a -> i `seq` (i + 1, f i a)) 0+{-# INLINE imapBL8 #-}++ifoldrBL8 :: (Int -> Char -> a -> a) -> a -> BL8.ByteString -> a+ifoldrBL8 f z xs = BL8.foldr (\ x g i -> i `seq` f i x (g (i+1))) (const z) xs 0+{-# INLINE ifoldrBL8 #-}++------------------------------------------------------------------------------+-- ByteString guts+------------------------------------------------------------------------------++-- | Conversion between 'Word8' and 'Char'. Should compile to a no-op.+w2c :: Word8 -> Char+w2c = unsafeChr . fromIntegral+{-# INLINE w2c #-}++-- | Unsafe conversion between 'Char' and 'Word8'. This is a no-op and+-- silently truncates to 8 bits Chars > '\255'. It is provided as+-- convenience for ByteString construction.+c2w :: Char -> Word8+c2w = fromIntegral . ord+{-# INLINE c2w #-}++-- | A way of creating ByteStrings outside the IO monad. The @Int@+-- argument gives the final size of the ByteString. Unlike+-- 'createAndTrim' the ByteString is not reallocated if the final size+-- is less than the estimated size.+unsafeCreate :: Int -> (Ptr Word8 -> IO ()) -> B.ByteString+unsafeCreate l f = unsafeDupablePerformIO (create l f)+{-# INLINE unsafeCreate #-}++-- | Create ByteString of size @l@ and use action @f@ to fill it's contents.+create :: Int -> (Ptr Word8 -> IO ()) -> IO B.ByteString+create l f = do+    fp <- mallocPlainForeignPtrBytes l+    withForeignPtr fp $ \p -> f p+#if MIN_VERSION_bytestring(0,11,0)+    return $! BI.BS fp l+#else+    return $! BI.PS fp 0 l+#endif+{-# INLINE create #-}
+ src/Control/Lens/Internal/CTypes.hs view
@@ -0,0 +1,28 @@+-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.CTypes+-- Copyright   :  (C) 2012-2016 Edward Kmett, (C) 2017 Ryan Scott+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-- In "Control.Lens.Wrapped", we need to muck around with the internals of the+-- newtypes in "Foreign.C.Types". Unfortunately, the exact types used varies+-- wildly from platform to platform, so trying to manage the imports necessary+-- to bring these types in scope can be unwieldy.+--+-- To make things easier, we use this module as a way to import everything+-- carte blanche that might be used internally in "Foreign.C.Types". For+-- now, this consists of all the exports from the "Data.Int" and "Data.Word"+-- modules, as well as the 'Ptr' type.+----------------------------------------------------------------------------+module Control.Lens.Internal.CTypes+  ( module Data.Int+  , Ptr+  , module Data.Word+  ) where++import Data.Int+import Data.Word+import Foreign.Ptr (Ptr)
+ src/Control/Lens/Internal/Context.hs view
@@ -0,0 +1,359 @@+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE RoleAnnotations #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Context+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+----------------------------------------------------------------------------+module Control.Lens.Internal.Context+  ( IndexedFunctor(..)+  , IndexedComonad(..)+  , IndexedComonadStore(..)+  , Sellable(..)+  , Context(..), Context'+  , Pretext(..), Pretext'+  , PretextT(..), PretextT'+  ) where++import Prelude ()++import Control.Arrow+import qualified Control.Category as C+import Control.Comonad+import Control.Comonad.Store.Class+import Control.Lens.Internal.Indexed+import Control.Lens.Internal.Prelude+import Data.Kind+import Data.Profunctor.Rep+import Prelude hiding ((.),id)++------------------------------------------------------------------------------+-- IndexedFunctor+------------------------------------------------------------------------------++-- | This is a Bob Atkey -style 2-argument indexed functor.+--+-- It exists as a superclass for 'IndexedComonad' and expresses the functoriality+-- of an 'IndexedComonad' in its third argument.+class IndexedFunctor w where+  ifmap :: (s -> t) -> w a b s -> w a b t++------------------------------------------------------------------------------+-- IndexedComonad+------------------------------------------------------------------------------++-- | This is a Bob Atkey -style 2-argument indexed comonad.+--+-- It exists as a superclass for 'IndexedComonad' and expresses the functoriality+-- of an 'IndexedComonad' in its third argument.+--+-- The notion of indexed monads is covered in more depth in Bob Atkey's+-- "Parameterized Notions of Computation" <http://bentnib.org/paramnotions-jfp.pdf>+-- and that construction is dualized here.+class IndexedFunctor w => IndexedComonad w where+  {-# MINIMAL iextract, (iduplicate | iextend) #-}++  -- | extract from an indexed comonadic value when the indices match.+  iextract :: w a a t -> t++  -- | duplicate an indexed comonadic value splitting the index.+  iduplicate :: w a c t -> w a b (w b c t)+  iduplicate = iextend id+  {-# INLINE iduplicate #-}++  -- | extend a indexed comonadic computation splitting the index.+  iextend :: (w b c t -> r) -> w a c t -> w a b r+  iextend f = ifmap f . iduplicate+  {-# INLINE iextend #-}++------------------------------------------------------------------------------+-- IndexedComonadStore+------------------------------------------------------------------------------++-- | This is an indexed analogue to 'ComonadStore' for when you are working with an+-- 'IndexedComonad'.+class IndexedComonad w => IndexedComonadStore w where+  -- | This is the generalization of 'pos' to an indexed comonad store.+  ipos :: w a c t -> a++  -- | This is the generalization of 'peek' to an indexed comonad store.+  ipeek :: c  -> w a c t -> t+  ipeek c = iextract . iseek c+  {-# INLINE ipeek #-}++  -- | This is the generalization of 'peeks' to an indexed comonad store.+  ipeeks :: (a -> c) -> w a c t -> t+  ipeeks f = iextract . iseeks f+  {-# INLINE ipeeks #-}++  -- | This is the generalization of 'seek' to an indexed comonad store.+  iseek :: b  -> w a c t -> w b c t++  -- | This is the generalization of 'seeks' to an indexed comonad store.+  iseeks :: (a -> b) -> w a c t -> w b c t++  -- | This is the generalization of 'experiment' to an indexed comonad store.+  iexperiment :: Functor f => (b -> f c) -> w b c t -> f t+  iexperiment bfc wbct = (`ipeek` wbct) <$> bfc (ipos wbct)+  {-# INLINE iexperiment #-}++  -- | We can always forget the rest of the structure of 'w' and obtain a simpler+  -- indexed comonad store model called 'Context'.+  context :: w a b t -> Context a b t+  context wabt = Context (`ipeek` wabt) (ipos wabt)+  {-# INLINE context #-}++------------------------------------------------------------------------------+-- Sellable+------------------------------------------------------------------------------++-- | This is used internally to construct a 'Control.Lens.Internal.Bazaar.Bazaar', 'Context' or 'Pretext'+-- from a singleton value.+class Corepresentable p => Sellable p w | w -> p where+  sell :: p a (w a b b)++------------------------------------------------------------------------------+-- Context+------------------------------------------------------------------------------++-- | The indexed store can be used to characterize a 'Control.Lens.Lens.Lens'+-- and is used by 'Control.Lens.Lens.cloneLens'.+--+-- @'Context' a b t@ is isomorphic to+-- @newtype 'Context' a b t = 'Context' { runContext :: forall f. 'Functor' f => (a -> f b) -> f t }@,+-- and to @exists s. (s, 'Control.Lens.Lens.Lens' s t a b)@.+--+-- A 'Context' is like a 'Control.Lens.Lens.Lens' that has already been applied to a some structure.+data Context a b t = Context (b -> t) a+-- type role Context representational representational representational++instance IndexedFunctor Context where+  ifmap f (Context g t) = Context (f . g) t+  {-# INLINE ifmap #-}++instance IndexedComonad Context where+  iextract   (Context f a) = f a+  {-# INLINE iextract #-}+  iduplicate (Context f a) = Context (Context f) a+  {-# INLINE iduplicate #-}+  iextend g  (Context f a) = Context (g . Context f) a+  {-# INLINE iextend #-}++instance IndexedComonadStore Context where+  ipos (Context _ a) = a+  {-# INLINE ipos #-}+  ipeek b (Context g _) = g b+  {-# INLINE ipeek #-}+  ipeeks f (Context g a) = g (f a)+  {-# INLINE ipeeks #-}+  iseek a (Context g _) = Context g a+  {-# INLINE iseek #-}+  iseeks f (Context g a) = Context g (f a)+  {-# INLINE iseeks #-}+  iexperiment f (Context g a) = g <$> f a+  {-# INLINE iexperiment #-}+  context = id+  {-# INLINE context #-}++instance Functor (Context a b) where+  fmap f (Context g t) = Context (f . g) t+  {-# INLINE fmap #-}++instance a ~ b => Comonad (Context a b) where+  extract   (Context f a) = f a+  {-# INLINE extract #-}+  duplicate (Context f a) = Context (Context f) a+  {-# INLINE duplicate #-}+  extend g  (Context f a) = Context (g . Context f) a+  {-# INLINE extend #-}++instance a ~ b => ComonadStore a (Context a b) where+  pos = ipos+  {-# INLINE pos #-}+  peek = ipeek+  {-# INLINE peek #-}+  peeks = ipeeks+  {-# INLINE peeks #-}+  seek = iseek+  {-# INLINE seek #-}+  seeks = iseeks+  {-# INLINE seeks #-}+  experiment = iexperiment+  {-# INLINE experiment #-}++instance Sellable (->) Context where+  sell = Context id+  {-# INLINE sell #-}++-- | @type 'Context'' a s = 'Context' a a s@+type Context' a = Context a a++------------------------------------------------------------------------------+-- Pretext+------------------------------------------------------------------------------++-- | This is a generalized form of 'Context' that can be repeatedly cloned with less+-- impact on its performance, and which permits the use of an arbitrary 'Conjoined'+-- 'Profunctor'+newtype Pretext p a b t = Pretext { runPretext :: forall f. Functor f => p a (f b) -> f t }+-- type role Pretext representational nominal nominal nominal++-- | @type 'Pretext'' p a s = 'Pretext' p a a s@+type Pretext' p a = Pretext p a a++instance IndexedFunctor (Pretext p) where+  ifmap f (Pretext k) = Pretext (fmap f . k)+  {-# INLINE ifmap #-}++instance Functor (Pretext p a b) where+  fmap = ifmap+  {-# INLINE fmap #-}++instance Conjoined p => IndexedComonad (Pretext p) where+  iextract (Pretext m) = runIdentity $ m (arr Identity)+  {-# INLINE iextract #-}+  iduplicate (Pretext m) = getCompose $ m (Compose #. distrib sell C.. sell)+  {-# INLINE iduplicate #-}++instance (a ~ b, Conjoined p) => Comonad (Pretext p a b) where+  extract = iextract+  {-# INLINE extract #-}+  duplicate = iduplicate+  {-# INLINE duplicate #-}++instance Conjoined p => IndexedComonadStore (Pretext p) where+  ipos (Pretext m) = getConst $ coarr m $ arr Const+  {-# INLINE ipos #-}+  ipeek a (Pretext m) = runIdentity $ coarr m $ arr (\_ -> Identity a)+  {-# INLINE ipeek #-}+  ipeeks f (Pretext m) = runIdentity $ coarr m $ arr (Identity . f)+  {-# INLINE ipeeks #-}+  iseek a (Pretext m) = Pretext (lmap (lmap (const a)) m)+  {-# INLINE iseek #-}+  iseeks f (Pretext m) = Pretext (lmap (lmap f) m)+  {-# INLINE iseeks #-}+  iexperiment f (Pretext m) = coarr m (arr f)+  {-# INLINE iexperiment #-}+  context (Pretext m) = coarr m (arr sell)+  {-# INLINE context #-}++instance (a ~ b, Conjoined p) => ComonadStore a (Pretext p a b) where+  pos = ipos+  {-# INLINE pos #-}+  peek = ipeek+  {-# INLINE peek #-}+  peeks = ipeeks+  {-# INLINE peeks #-}+  seek = iseek+  {-# INLINE seek #-}+  seeks = iseeks+  {-# INLINE seeks #-}+  experiment = iexperiment+  {-# INLINE experiment #-}++instance Corepresentable p => Sellable p (Pretext p) where+  sell = cotabulate $ \ w -> Pretext (`cosieve` w)+  {-# INLINE sell #-}++------------------------------------------------------------------------------+-- PretextT+------------------------------------------------------------------------------++++-- | This is a generalized form of 'Context' that can be repeatedly cloned with less+-- impact on its performance, and which permits the use of an arbitrary 'Conjoined'+-- 'Profunctor'.+--+-- The extra phantom 'Functor' is used to let us lie and claim+-- 'Control.Lens.Getter.Getter'-compatibility under limited circumstances.+-- This is used internally to permit a number of combinators to gracefully+-- degrade when applied to a 'Control.Lens.Fold.Fold' or+-- 'Control.Lens.Getter.Getter'.+newtype PretextT p (g :: Type -> Type) a b t = PretextT { runPretextT :: forall f. Functor f => p a (f b) -> f t }++-- really we want PretextT p g a b t to permit the last 3 arguments to be representational iff p and f accept representational arguments+-- but that isn't currently an option in GHC+type role PretextT representational nominal nominal nominal nominal++-- | @type 'PretextT'' p g a s = 'PretextT' p g a a s@+type PretextT' p g a = PretextT p g a a++instance IndexedFunctor (PretextT p g) where+  ifmap f (PretextT k) = PretextT (fmap f . k)+  {-# INLINE ifmap #-}++instance Functor (PretextT p g a b) where+  fmap = ifmap+  {-# INLINE fmap #-}++instance Conjoined p => IndexedComonad (PretextT p g) where+  iextract (PretextT m) = runIdentity $ m (arr Identity)+  {-# INLINE iextract #-}+  iduplicate (PretextT m) = getCompose $ m (Compose #. distrib sell C.. sell)+  {-# INLINE iduplicate #-}++instance (a ~ b, Conjoined p) => Comonad (PretextT p g a b) where+  extract = iextract+  {-# INLINE extract #-}+  duplicate = iduplicate+  {-# INLINE duplicate #-}++instance Conjoined p => IndexedComonadStore (PretextT p g) where+  ipos (PretextT m) = getConst $ coarr m $ arr Const+  {-# INLINE ipos #-}+  ipeek a (PretextT m) = runIdentity $ coarr m $ arr (\_ -> Identity a)+  {-# INLINE ipeek #-}+  ipeeks f (PretextT m) = runIdentity $ coarr m $ arr (Identity . f)+  {-# INLINE ipeeks #-}+  iseek a (PretextT m) = PretextT (lmap (lmap (const a)) m)+  {-# INLINE iseek #-}+  iseeks f (PretextT m) = PretextT (lmap (lmap f) m)+  {-# INLINE iseeks #-}+  iexperiment f (PretextT m) = coarr m (arr f)+  {-# INLINE iexperiment #-}+  context (PretextT m) = coarr m (arr sell)+  {-# INLINE context #-}++instance (a ~ b, Conjoined p) => ComonadStore a (PretextT p g a b) where+  pos = ipos+  {-# INLINE pos #-}+  peek = ipeek+  {-# INLINE peek #-}+  peeks = ipeeks+  {-# INLINE peeks #-}+  seek = iseek+  {-# INLINE seek #-}+  seeks = iseeks+  {-# INLINE seeks #-}+  experiment = iexperiment+  {-# INLINE experiment #-}++instance Corepresentable p => Sellable p (PretextT p g) where+  sell = cotabulate $ \ w -> PretextT (`cosieve` w)+  {-# INLINE sell #-}++instance (Profunctor p, Contravariant g) => Contravariant (PretextT p g a b) where+  contramap _ = (<$) (error "contramap: PretextT")+  {-# INLINE contramap #-}++------------------------------------------------------------------------------+-- Utilities+------------------------------------------------------------------------------++-- | We can convert any 'Conjoined' 'Profunctor' to a function,+-- possibly losing information about an index in the process.+coarr :: (Representable q, Comonad (Rep q)) => q a b -> a -> b+coarr qab = extract . sieve qab+{-# INLINE coarr #-}
+ src/Control/Lens/Internal/Deque.hs view
@@ -0,0 +1,211 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE PatternGuards #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}++#include "lens-common.h"+-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Deque+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-- This module is designed to be imported qualified.+-----------------------------------------------------------------------------+module Control.Lens.Internal.Deque+  ( Deque(..)+  , size+  , fromList+  , null+  , singleton+  ) where++import Prelude ()++import Control.Lens.Cons+import Control.Lens.Fold+import Control.Lens.Indexed hiding ((<.>))+import Control.Lens.Internal.Prelude hiding (null)+import Control.Lens.Iso+import Control.Lens.Lens+import Control.Lens.Prism+import Control.Monad+import Data.Foldable (toList)+import Data.Function+import Data.Functor.Bind+import Data.Functor.Plus+import Data.Functor.Reverse++-- $setup+-- >>> import Control.Applicative (empty)++-- | A Banker's deque based on Chris Okasaki's \"Purely Functional Data Structures\"+data Deque a = BD !Int [a] !Int [a]+  deriving Show++-- | /O(1)/. Determine if a 'Deque' is 'empty'.+--+-- >>> Control.Lens.Internal.Deque.null empty+-- True+--+-- >>> Control.Lens.Internal.Deque.null (singleton 1)+-- False+null :: Deque a -> Bool+null (BD lf _ lr _) = lf + lr == 0+{-# INLINE null #-}++-- | /O(1)/. Generate a singleton 'Deque'+--+-- >>> singleton 1+-- BD 1 [1] 0 []+singleton :: a -> Deque a+singleton a = BD 1 [a] 0 []+{-# INLINE singleton #-}++-- | /O(1)/. Calculate the size of a 'Deque'+--+-- >>> size (fromList [1,4,6])+-- 3+size :: Deque a -> Int+size (BD lf _ lr _) = lf + lr+{-# INLINE size #-}++-- | /O(n)/ amortized. Construct a 'Deque' from a list of values.+--+-- >>> fromList [1,2]+-- BD 1 [1] 1 [2]+fromList :: [a] -> Deque a+fromList = foldr cons empty+{-# INLINE fromList #-}++instance Eq a => Eq (Deque a) where+  (==) = (==) `on` toList+  {-# INLINE (==) #-}++instance Ord a => Ord (Deque a) where+  compare = compare `on` toList+  {-# INLINE compare #-}++instance Functor Deque where+  fmap h (BD lf f lr r) = BD lf (fmap h f) lr (fmap h r)+  {-# INLINE fmap #-}++instance FunctorWithIndex Int Deque where+  imap h (BD lf f lr r) = BD lf (imap h f) lr (imap (\j -> h (n - j)) r)+    where !n = lf + lr++instance Apply Deque where+  fs <.> as = fromList (toList fs <.> toList as)+  {-# INLINE (<.>) #-}++instance Applicative Deque where+  pure a = BD 1 [a] 0 []+  {-# INLINE pure #-}+  fs <*> as = fromList (toList fs <*> toList as)+  {-# INLINE (<*>) #-}++instance Alt Deque where+  xs <!> ys+    | size xs < size ys = foldr cons ys xs+    | otherwise         = foldl snoc xs ys+  {-# INLINE (<!>) #-}++instance Plus Deque where+  zero = BD 0 [] 0 []+  {-# INLINE zero #-}++instance Alternative Deque where+  empty = BD 0 [] 0 []+  {-# INLINE empty #-}+  xs <|> ys+    | size xs < size ys = foldr cons ys xs+    | otherwise         = foldl snoc xs ys+  {-# INLINE (<|>) #-}++instance Reversing (Deque a) where+  reversing (BD lf f lr r) = BD lr r lf f+  {-# INLINE reversing #-}++instance Bind Deque where+  ma >>- k = fromList (toList ma >>= toList . k)+  {-# INLINE (>>-) #-}++instance Monad Deque where+  return = pure+  {-# INLINE return #-}+  ma >>= k = fromList (toList ma >>= toList . k)+  {-# INLINE (>>=) #-}++instance MonadPlus Deque where+  mzero = empty+  {-# INLINE mzero #-}+  mplus = (<|>)+  {-# INLINE mplus #-}++instance Foldable Deque where+  foldMap h (BD _ f _ r) = foldMap h f `mappend` getDual (foldMap (Dual #. h) r)+  {-# INLINE foldMap #-}++instance FoldableWithIndex Int Deque where+  ifoldMap h (BD lf f lr r) = ifoldMap h f `mappend` getDual (ifoldMap (\j -> Dual #. h (n - j)) r)+    where !n = lf + lr+  {-# INLINE ifoldMap #-}++instance Traversable Deque where+  traverse h (BD lf f lr r) = (BD lf ?? lr) <$> traverse h f <*> backwards traverse h r+  {-# INLINE traverse #-}++instance TraversableWithIndex Int Deque where+  itraverse h (BD lf f lr r) = (\f' r' -> BD lr f' lr (getReverse r')) <$> itraverse h f <*> itraverse (\j -> h (n - j)) (Reverse r)+    where !n = lf + lr+  {-# INLINE itraverse #-}++instance Semigroup (Deque a) where+  xs <> ys+    | size xs < size ys = foldr cons ys xs+    | otherwise         = foldl snoc xs ys+  {-# INLINE (<>) #-}++instance Monoid (Deque a) where+  mempty = BD 0 [] 0 []+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  mappend xs ys+    | size xs < size ys = foldr cons ys xs+    | otherwise         = foldl snoc xs ys+  {-# INLINE mappend #-}+#endif++-- | Check that a 'Deque' satisfies the balance invariants and rebalance if not.+check :: Int -> [a] -> Int -> [a] -> Deque a+check lf f lr r+  | lf > 3*lr + 1, i <- div (lf + lr) 2, (f',f'') <- splitAt i f = BD i f' (lf + lr - i) (r ++ reverse f'')+  | lr > 3*lf + 1, j <- div (lf + lr) 2, (r',r'') <- splitAt j r = BD (lf + lr - j) (f ++ reverse r'') j r'+  | otherwise = BD lf f lr r+{-# INLINE check #-}++instance Cons (Deque a) (Deque b) a b where+  _Cons = prism (\(x,BD lf f lr r) -> check (lf + 1) (x : f) lr r) $ \ (BD lf f lr r) ->+    if lf + lr == 0+    then Left empty+    else Right $ case f of+      []     -> case r of+                  y:_ -> (y, empty)+                  []  -> error "Control.Lens.Internal.Deque._Cons: Internal check failed"+      (x:xs) -> (x, check (lf - 1) xs lr r)+  {-# INLINE _Cons #-}++instance Snoc (Deque a) (Deque b) a b where+  _Snoc = prism (\(BD lf f lr r,x) -> check lf f (lr + 1) (x : r)) $ \ (BD lf f lr r) ->+    if lf + lr == 0+    then Left empty+    else Right $ case r of+      []     -> case f of+                  y:_ -> (empty, y)+                  []  -> error "Control.Lens.Internal.Deque._Snoc: Internal check failed"+      (x:xs) -> (check lf f (lr - 1) xs, x)+  {-# INLINE _Snoc #-}
+ src/Control/Lens/Internal/Doctest.hs view
@@ -0,0 +1,43 @@+-- | This module exists for the sole purpose of redefining the 'head' and 'tail'+-- functions (which are normally provided by the 'Prelude') so that they can be+-- used in the doctests of 'Data.Data.Lens'.+--+-- The 'head' and 'tail' functions are partial, and as of GHC 9.8, there is a+-- @-Wx-partial@ warning (implied by @-Wall@) that triggers any time you use+-- either of these functions. This is a fairly reasonable default in most+-- settings, but there are a handful of doctests in 'Data.Data.Lens' that do in+-- fact rely on 'head' and 'tail' being partial functions. These doctests+-- demonstrate that various functions in 'Data.Data.Lens' can recover from+-- exceptions that are thrown due to partiality (see, for instance, the @upon@+-- function).+--+-- One possible workaround would be to disable @-Wx-partial@. We don't want to+-- disable the warning for /all/ code in @lens@, however—we only want to+-- disable it for a particular group of doctests. It is rather tricky to achieve+-- this level of granularity, unfortunately. This is because tools like+-- @cabal-docspec@ rely on GHCi to work, and the statefulness of GHCi's @:set@+-- command means that disabling @-Wx-partial@ might leak into other modules'+-- doctests, which we don't want.+--+-- Instead, we opt to redefine our own versions of 'head' and 'tail' here, which+-- do not trigger any @-Wx-partial@ warnings, and use them in the+-- 'Data.Data.Lens' doctests. This has no impact on anyone reading the doctests,+-- as these functions will look indistinguishable from the 'head' and 'tail'+-- functions in the 'Prelude'. One consequence of this design is that we must+-- export the 'Control.Lens.Internal.Doctest' module, as GHCi (and therefore+-- @cabal-docspec@) won't be able to import it otherwise. Despite this technical+-- oddity, this module should be thought of as internal to @lens@.+module Control.Lens.Internal.Doctest+  ( head+  , tail+  ) where++import Prelude hiding (head, tail)++head :: [a] -> a+head (x:_) = x+head []    = error "head: empty list"++tail :: [a] -> [a]+tail (_:xs) = xs+tail []     = error "tail: empty list"
+ src/Control/Lens/Internal/Exception.hs view
@@ -0,0 +1,178 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE RoleAnnotations #-}++#include "lens-common.h"++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Exception+-- Copyright   :  (C) 2013-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-- This module uses dirty tricks to generate a 'Handler' from an arbitrary+-- 'Fold'.+----------------------------------------------------------------------------+module Control.Lens.Internal.Exception+  ( Handleable(..)+  , HandlingException(..)+  ) where++import Control.Exception as Exception+import Control.Lens.Fold+import Control.Lens.Getter+import Control.Monad.Catch as Catch+import Data.Kind+import Data.Monoid+import Data.Proxy+import Data.Reflection+import Data.Typeable++------------------------------------------------------------------------------+-- Handlers+------------------------------------------------------------------------------++-- | Both @exceptions@ and "Control.Exception" provide a 'Handler' type.+--+-- This lets us write combinators to build handlers that are agnostic about the choice of+-- which of these they use.+class Handleable e (m :: Type -> Type) (h :: Type -> Type) | h -> e m where+  -- | This builds a 'Handler' for just the targets of a given 'Control.Lens.Type.Prism' (or any 'Getter', really).+  --+  -- @+  -- 'catches' ... [ 'handler' 'Control.Exception.Lens._AssertionFailed' (\s -> 'print' '$' \"Assertion Failed\\n\" '++' s)+  --             , 'handler' 'Control.Exception.Lens._ErrorCall' (\s -> 'print' '$' \"Error\\n\" '++' s)+  --             ]+  -- @+  --+  -- This works ith both the 'Exception.Handler' type provided by @Control.Exception@:+  --+  -- @+  -- 'handler' :: 'Getter'     'SomeException' a -> (a -> 'IO' r) -> 'Exception.Handler' r+  -- 'handler' :: 'Fold'       'SomeException' a -> (a -> 'IO' r) -> 'Exception.Handler' r+  -- 'handler' :: 'Control.Lens.Prism.Prism''     'SomeException' a -> (a -> 'IO' r) -> 'Exception.Handler' r+  -- 'handler' :: 'Control.Lens.Lens.Lens''      'SomeException' a -> (a -> 'IO' r) -> 'Exception.Handler' r+  -- 'handler' :: 'Control.Lens.Traversal.Traversal'' 'SomeException' a -> (a -> 'IO' r) -> 'Exception.Handler' r+  -- @+  --+  -- and with the 'Catch.Handler' type provided by @Control.Monad.Catch@:+  --+  -- @+  -- 'handler' :: 'Getter'     'SomeException' a -> (a -> m r) -> 'Catch.Handler' m r+  -- 'handler' :: 'Fold'       'SomeException' a -> (a -> m r) -> 'Catch.Handler' m r+  -- 'handler' :: 'Control.Lens.Prism.Prism''     'SomeException' a -> (a -> m r) -> 'Catch.Handler' m r+  -- 'handler' :: 'Control.Lens.Lens.Lens''      'SomeException' a -> (a -> m r) -> 'Catch.Handler' m r+  -- 'handler' :: 'Control.Lens.Traversal.Traversal'' 'SomeException' a -> (a -> m r) -> 'Catch.Handler' m r+  -- @+  --+  -- and with the 'Control.Monad.Error.Lens.Handler' type provided by @Control.Monad.Error.Lens@:+  --+  -- @+  -- 'handler' :: 'Getter'     e a -> (a -> m r) -> 'Control.Monad.Error.Lens.Handler' e m r+  -- 'handler' :: 'Fold'       e a -> (a -> m r) -> 'Control.Monad.Error.Lens.Handler' e m r+  -- 'handler' :: 'Control.Lens.Prism.Prism''     e a -> (a -> m r) -> 'Control.Monad.Error.Lens.Handler' e m r+  -- 'handler' :: 'Control.Lens.Lens.Lens''      e a -> (a -> m r) -> 'Control.Monad.Error.Lens.Handler' e m r+  -- 'handler' :: 'Control.Lens.Traversal.Traversal'' e a -> (a -> m r) -> 'Control.Monad.Error.Lens.Handler' e m r+  -- @+  handler :: Typeable a => Getting (First a) e a -> (a -> m r) -> h r++  -- | This builds a 'Handler' for just the targets of a given 'Control.Lens.Prism.Prism' (or any 'Getter', really).+  -- that ignores its input and just recovers with the stated monadic action.+  --+  -- @+  -- 'catches' ... [ 'handler_' 'Control.Exception.Lens._NonTermination' ('return' \"looped\")+  --             , 'handler_' 'Control.Exception.Lens._StackOverflow' ('return' \"overflow\")+  --             ]+  -- @+  --+  -- This works with the 'Exception.Handler' type provided by @Control.Exception@:+  --+  -- @+  -- 'handler_' :: 'Getter'     'SomeException' a -> 'IO' r -> 'Exception.Handler' r+  -- 'handler_' :: 'Fold'       'SomeException' a -> 'IO' r -> 'Exception.Handler' r+  -- 'handler_' :: 'Control.Lens.Prism.Prism''     'SomeException' a -> 'IO' r -> 'Exception.Handler' r+  -- 'handler_' :: 'Control.Lens.Lens.Lens''      'SomeException' a -> 'IO' r -> 'Exception.Handler' r+  -- 'handler_' :: 'Control.Lens.Traversal.Traversal'' 'SomeException' a -> 'IO' r -> 'Exception.Handler' r+  -- @+  --+  -- and with the 'Catch.Handler' type provided by @Control.Monad.Catch@:+  --+  -- @+  -- 'handler_' :: 'Getter'     'SomeException' a -> m r -> 'Catch.Handler' m r+  -- 'handler_' :: 'Fold'       'SomeException' a -> m r -> 'Catch.Handler' m r+  -- 'handler_' :: 'Control.Lens.Prism.Prism''     'SomeException' a -> m r -> 'Catch.Handler' m r+  -- 'handler_' :: 'Control.Lens.Lens.Lens''      'SomeException' a -> m r -> 'Catch.Handler' m r+  -- 'handler_' :: 'Control.Lens.Traversal.Traversal'' 'SomeException' a -> m r -> 'Catch.Handler' m r+  -- @+  --+  -- and with the 'Control.Monad.Error.Lens.Handler' type provided by @Control.Monad.Error.Lens@:+  --+  -- @+  -- 'handler_' :: 'Getter'     e a -> m r -> 'Control.Monad.Error.Lens.Handler' e m r+  -- 'handler_' :: 'Fold'       e a -> m r -> 'Control.Monad.Error.Lens.Handler' e m r+  -- 'handler_' :: 'Control.Lens.Prism.Prism''     e a -> m r -> 'Control.Monad.Error.Lens.Handler' e m r+  -- 'handler_' :: 'Control.Lens.Lens.Lens''      e a -> m r -> 'Control.Monad.Error.Lens.Handler' e m r+  -- 'handler_' :: 'Control.Lens.Traversal.Traversal'' e a -> m r -> 'Control.Monad.Error.Lens.Handler' e m r+  -- @+  handler_ :: Typeable a => Getting (First a) e a -> m r -> h r+  handler_ l = handler l . const+  {-# INLINE handler_ #-}++instance Handleable SomeException IO Exception.Handler where+  handler = handlerIO++instance Typeable m => Handleable SomeException m (Catch.Handler m) where+  handler = handlerCatchIO++handlerIO :: forall a r. Typeable a => Getting (First a) SomeException a -> (a -> IO r) -> Exception.Handler r+handlerIO l f = reifyTypeable (preview l) $ \ (_ :: Proxy s) -> Exception.Handler (\(Handling a :: Handling a s IO) -> f a)++handlerCatchIO :: forall m a r. (Typeable a, Typeable m) => Getting (First a) SomeException a -> (a -> m r) -> Catch.Handler m r+handlerCatchIO l f = reifyTypeable (preview l) $ \ (_ :: Proxy s) -> Catch.Handler (\(Handling a :: Handling a s m) -> f a)++------------------------------------------------------------------------------+-- Helpers+------------------------------------------------------------------------------++-- | There was an 'Exception' caused by abusing the internals of a 'Handler'.+data HandlingException = HandlingException deriving Show++instance Exception HandlingException++{-+-- | This supplies a globally unique set of IDs so we can hack around the default use of 'cast' in 'SomeException'+-- if someone, somehow, somewhere decides to reach in and catch and rethrow a @Handling@ 'Exception' by existentially+-- opening a 'Handler' that uses it.+supply :: IORef Int+supply = unsafePerformIO $ newIORef 0+{-# NOINLINE supply #-}+-}++-- | This permits the construction of an \"impossible\" 'Control.Exception.Handler' that matches only if some function does.+newtype Handling a s (m :: Type -> Type) = Handling a++type role Handling representational nominal nominal++-- The @Handling@ wrapper is uninteresting, and should never be thrown, so you won't get much benefit here.+instance Show (Handling a s m) where+  showsPrec d _ = showParen (d > 10) $ showString "Handling ..."+  {-# INLINE showsPrec #-}++instance ( Reifies s (SomeException -> Maybe a)+         , Typeable a, Typeable s+         , Typeable m+         )+    => Exception (Handling a (s :: Type) m) where+  toException _ = SomeException HandlingException+  {-# INLINE toException #-}+  fromException = fmap Handling . reflect (Proxy :: Proxy s)+  {-# INLINE fromException #-}
+ src/Control/Lens/Internal/FieldTH.hs view
@@ -0,0 +1,691 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE PatternGuards #-}+#if __GLASGOW_HASKELL__ >= 800+{-# LANGUAGE TemplateHaskellQuotes #-}+#else+{-# LANGUAGE TemplateHaskell #-}+#endif+#ifdef TRUSTWORTHY+# if MIN_VERSION_template_haskell(2,12,0)+{-# LANGUAGE Safe #-}+# else+{-# LANGUAGE Trustworthy #-}+# endif+#endif++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.FieldTH+-- Copyright   :  (C) 2014-2016 Edward Kmett, (C) 2014 Eric Mertens+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-----------------------------------------------------------------------------++module Control.Lens.Internal.FieldTH+  ( LensRules(..)+  , FieldNamer+  , DefName(..)+  , ClassyNamer+  , makeFieldOptics+  , makeFieldOpticsForDec+  , makeFieldOpticsForDec'+  , HasFieldClasses+  ) where++import Prelude ()++import Control.Lens.At+import Control.Lens.Fold+import Control.Lens.Indexed+import Control.Lens.Internal.TH+import Control.Lens.Internal.Prelude+import Control.Lens.Lens+import Control.Lens.Plated+import Control.Lens.Prism+import Control.Lens.Setter+import Control.Lens.Getter+import Control.Lens.Tuple+import Control.Lens.Traversal+import Control.Monad+import Control.Monad.State+import Language.Haskell.TH.Lens+import Language.Haskell.TH+import qualified Language.Haskell.TH.Datatype as D+import qualified Language.Haskell.TH.Datatype.TyVarBndr as D+import Data.Maybe (fromMaybe,isJust,maybeToList)+import Data.List (nub)+import Data.Either (partitionEithers)+import Data.Semigroup (Any (..))+import Data.Set.Lens+import           Data.Map ( Map )+import           Data.Set ( Set )+import qualified Data.Set as Set+import qualified Data.Map as Map+import qualified Data.Traversable as T++------------------------------------------------------------------------+-- Field generation entry point+------------------------------------------------------------------------+++-- | Compute the field optics for the type identified by the given type name.+-- Lenses will be computed when possible, Traversals otherwise.+makeFieldOptics :: LensRules -> Name -> DecsQ+makeFieldOptics rules = (`evalStateT` Set.empty) . makeFieldOpticsForDatatype rules <=< D.reifyDatatype++makeFieldOpticsForDec :: LensRules -> Dec -> DecsQ+makeFieldOpticsForDec rules = (`evalStateT` Set.empty) . makeFieldOpticsForDec' rules++makeFieldOpticsForDec' :: LensRules -> Dec -> HasFieldClasses [Dec]+makeFieldOpticsForDec' rules = makeFieldOpticsForDatatype rules <=< lift . D.normalizeDec++-- | Compute the field optics for a deconstructed datatype Dec+-- When possible build an Iso otherwise build one optic per field.+makeFieldOpticsForDatatype :: LensRules -> D.DatatypeInfo -> HasFieldClasses [Dec]+makeFieldOpticsForDatatype rules info =+  do perDef <- lift $ do+       fieldCons <- traverse normalizeConstructor cons+       let allFields  = toListOf (folded . _2 . folded . _1 . folded) fieldCons+       let defCons    = over normFieldLabels (expandName allFields) fieldCons+           allDefs    = setOf (normFieldLabels . folded . _1) defCons+       T.sequenceA (Map.fromSet (buildScaffold rules s defCons) allDefs)++     let defs = Map.toList perDef+     case _classyLenses rules tyName of+       Just (className, methodName) ->+         makeClassyDriver rules className methodName s defs+       Nothing -> do decss <- traverse (makeFieldOptic rules) defs+                     return (concat decss)++  where+  tyName = D.datatypeName     info+  s      = datatypeTypeKinded info+  cons   = D.datatypeCons     info++  -- Traverse the field labels of a normalized constructor+  normFieldLabels :: Traversal [(Name,[(a,Type)])] [(Name,[(b,Type)])] a b+  normFieldLabels = traverse . _2 . traverse . _1++  -- Map a (possibly missing) field's name to zero-to-many optic definitions+  expandName :: [Name] -> Maybe Name -> [(DefName, Maybe Name)]+  expandName allFields mName = (\x -> (x, mName)) <$> (maybeToList mName >>= _fieldToDef rules tyName allFields)++-- | Normalized the Con type into a uniform positional representation,+-- eliminating the variance between records, infix constructors, and normal+-- constructors.+normalizeConstructor ::+  D.ConstructorInfo ->+  Q (Name, [(Maybe Name, Type)]) -- ^ constructor name, field name, field type++normalizeConstructor con =+  return (D.constructorName con,+          zipWith checkForExistentials fieldNames (D.constructorFields con))+  where+    fieldNames =+      case D.constructorVariant con of+        D.RecordConstructor xs -> fmap Just xs+        D.NormalConstructor    -> repeat Nothing+        D.InfixConstructor     -> repeat Nothing++    -- Fields mentioning existentially quantified types are not+    -- elligible for TH generated optics.+    checkForExistentials _ fieldtype+      | any (\tv -> D.tvName tv `Set.member` used) unallowable+      = (Nothing, fieldtype)+      where+        used        = setOf typeVars fieldtype+        unallowable = D.constructorVars con+    checkForExistentials fieldname fieldtype = (fieldname, fieldtype)++data OpticType = GetterType | LensType | IsoType++-- | Compute the positional location of the fields involved in+-- each constructor for a given optic definition as well as the+-- type of clauses to generate and the type to annotate the declaration+-- with.+buildScaffold ::+  LensRules                                                                            ->+  Type                                        {- ^ outer type                       -} ->+  [(Name, [([(DefName, Maybe Name)], Type)])] {- ^ normalized constructors          -} ->+  DefName                                     {- ^ target definition                -} ->+  Q (OpticType, OpticStab, [(Name, Int, [(Maybe Name, Int)])])+              {- ^ optic type, definition type, field count, target fields -}+buildScaffold rules s cons defName =++  do (s',t,a,b) <- buildStab s (concatMap snd (consForDef <&> _2 . mapped . _Right %~ snd))++     let defType+           | Just (_,cx,a') <- preview _ForallT a =+               let optic | lensCase  = getterTypeName+                         | otherwise = foldTypeName+               in OpticSa cx optic s' a'++           -- Getter and Fold are always simple+           | not (_allowUpdates rules) =+               let optic | lensCase  = getterTypeName+                         | otherwise = foldTypeName+               in OpticSa [] optic s' a++           -- Generate simple Lens and Traversal where possible+           | _simpleLenses rules || s' == t && a == b =+               let optic | isoCase && _allowIsos rules = iso'TypeName+                         | lensCase                    = lens'TypeName+                         | otherwise                   = traversal'TypeName+               in OpticSa [] optic s' a++           -- Generate type-changing Lens and Traversal otherwise+           | otherwise =+               let optic | isoCase && _allowIsos rules = isoTypeName+                         | lensCase                    = lensTypeName+                         | otherwise                   = traversalTypeName+               in OpticStab optic s' t a b++         opticType | has _ForallT a            = GetterType+                   | not (_allowUpdates rules) = GetterType+                   | isoCase                   = IsoType+                   | otherwise                 = LensType++     return (opticType, defType, scaffolds)+  where+  consForDef :: [(Name, [Either Type (Maybe Name, Type)])]+  consForDef = over (mapped . _2 . mapped) categorize cons++  scaffolds :: [(Name, Int, [(Maybe Name, Int)])]+  scaffolds = [ (n, length ts, (\(a, b) -> (b, a)) <$> ts ^@.. folded <. _Right . _1) | (n,ts) <- consForDef ]++  -- Right: types for this definition+  -- Left : other types+  categorize :: ([(DefName, Maybe Name)], Type) -> Either Type (Maybe Name, Type)+  categorize (defNames, t) =+    case lookup defName defNames of+    Just c -> Right (c, t)+    Nothing -> Left t++  lensCase :: Bool+  lensCase = all (\x -> lengthOf (_2 . folded . _Right) x == 1) consForDef++  isoCase :: Bool+  isoCase = case scaffolds of+              [(_,1,[(_, 0)])] -> True+              _                -> False+++data OpticStab = OpticStab     Name Type Type Type Type+               | OpticSa   Cxt Name Type Type++stabToType :: OpticStab -> Type+stabToType (OpticStab  c s t a b) = quantifyType [] (c `conAppsT` [s,t,a,b])+stabToType (OpticSa cx c s   a  ) = quantifyType cx (c `conAppsT` [s,a])++stabToContext :: OpticStab -> Cxt+stabToContext OpticStab{}        = []+stabToContext (OpticSa cx _ _ _) = cx++stabToOptic :: OpticStab -> Name+stabToOptic (OpticStab c _ _ _ _) = c+stabToOptic (OpticSa _ c _ _) = c++stabToS :: OpticStab -> Type+stabToS (OpticStab _ s _ _ _) = s+stabToS (OpticSa _ _ s _) = s++stabToA :: OpticStab -> Type+stabToA (OpticStab _ _ _ a _) = a+stabToA (OpticSa _ _ _ a) = a++-- | Compute the s t a b types given the outer type 's' and the+-- categorized field types. Left for fixed and Right for visited.+-- These types are "raw" and will be packaged into an 'OpticStab'+-- shortly after creation.+buildStab :: Type -> [Either Type Type] -> Q (Type,Type,Type,Type)+buildStab s categorizedFields =+  do (subA,a) <- unifyTypes targetFields+     let s' = applyTypeSubst subA s++     -- compute possible type changes+     sub <- T.sequenceA (Map.fromSet (newName . nameBase) unfixedTypeVars)+     let (t,b) = over both (substTypeVars sub) (s',a)++     return (s',t,a,b)++  where+  (fixedFields, targetFields) = partitionEithers categorizedFields++  fixedTypeVars, unfixedTypeVars :: Set Name+  fixedTypeVars   = closeOverKinds $ setOf typeVars fixedFields+  unfixedTypeVars = setOf typeVars s Set.\\ fixedTypeVars++  -- Compute the kind variables that appear in the kind of a type variable+  -- binder. For example, @kindVarsOfTvb (x :: (a, b)) = (x, {a, b})@. If a+  -- type variable binder lacks an explicit kind annotation, this+  -- conservatively assumes that there are no kind variables. For example,+  -- @kindVarsOfTvb (y) = (y, {})@.+  kindVarsOfTvb :: D.TyVarBndr_ flag -> (Name, Set Name)+  kindVarsOfTvb = D.elimTV (\n   -> (n, Set.empty))+                           (\n k -> (n, setOf typeVars k))++  -- For each type variable name that appears in @s@, map to the kind variables+  -- that appear in that type variable's kind.+  sKindVarMap :: Map Name (Set Name)+  sKindVarMap = Map.fromList $ map kindVarsOfTvb $ D.freeVariablesWellScoped [s]++  lookupSKindVars :: Name -> Set Name+  lookupSKindVars n = fromMaybe Set.empty $ Map.lookup n sKindVarMap++  -- Consider this example (adapted from #972):+  --+  --   data Dart (s :: k) = Dart { _arc :: Proxy s, _direction :: Int }+  --   $(makeLenses ''Dart)+  --+  -- When generating a Lens for `direction`, the type variable `s` should be+  -- fixed. But note that (s :: k), and as a result, the kind variable `k`+  -- needs to be fixed as well. This is because a type like this would be+  -- ill kinded:+  --+  --   direction :: Lens (Dart (s :: k1)) (Dart (s :: k2)) Direction Direction+  --+  -- However, only `s` is mentioned syntactically in the type of `_arc`, so we+  -- have to infer that `k` is mentioned in the kind of `s`. We accomplish this+  -- with `closeOverKinds`, which does the following:+  --+  -- 1. Use freeVariablesWellScoped to compute the free type variables of+  --    `Dart (s :: k)`, which gives us `(s :: k)`.+  -- 2. For each type variable name in `Proxy s`, the type of `_arc`, look up+  --    the kind variables in the type variable's kind. In the case of `s`,+  --    the only kind variable is `k`.+  -- 3. Add these kind variables to the set of fixed type variables.+  closeOverKinds :: Set Name -> Set Name+  closeOverKinds st = foldl' Set.union Set.empty (Set.map lookupSKindVars st) `Set.union` st++-- | Build the signature and definition for a single field optic.+-- In the case of a singleton constructor irrefutable matches are+-- used to enable the resulting lenses to be used on a bottom value.+makeFieldOptic ::+  LensRules ->+  (DefName, (OpticType, OpticStab, [(Name, Int, [(Maybe Name, Int)])])) ->+  HasFieldClasses [Dec]+makeFieldOptic rules (defName, (opticType, defType, cons)) = do+  locals <- get+  addName+  lift $ do cls <- mkCls locals+            T.sequenceA (cls ++ sig ++ def)+  where+  mkCls locals = case defName of+                 MethodName c n | _generateClasses rules ->+                  do classExists <- isJust <$> lookupTypeName (show c)+                     return (if classExists || Set.member c locals then [] else [makeFieldClass defType c n])+                 _ -> return []++  addName = case defName of+            MethodName c _ -> addFieldClassName c+            _              -> return ()++  sig = case defName of+          _ | not (_generateSigs rules) -> []+          TopName n -> [sigD n (return (stabToType defType))]+          MethodName{} -> []++  fun n = funD n clauses : inlinePragma n++  def = case defName of+          TopName n      -> fun n+          MethodName c n -> [makeFieldInstance defType c (fun n)]++  clauses = makeFieldClauses rules opticType cons++------------------------------------------------------------------------+-- Classy class generator+------------------------------------------------------------------------+++makeClassyDriver ::+  LensRules ->+  Name ->+  Name ->+  Type {- ^ Outer 's' type -} ->+  [(DefName, (OpticType, OpticStab, [(Name, Int, [(Maybe Name, Int)])]))] ->+  HasFieldClasses [Dec]+makeClassyDriver rules className methodName s defs = T.sequenceA (cls ++ inst)++  where+  cls | _generateClasses rules = [lift $ makeClassyClass className methodName s defs]+      | otherwise = []++  inst = [makeClassyInstance rules className methodName s defs]+++makeClassyClass ::+  Name ->+  Name ->+  Type {- ^ Outer 's' type -} ->+  [(DefName, (OpticType, OpticStab, [(Name, Int, [(Maybe Name, Int)])]))] ->+  DecQ+makeClassyClass className methodName s defs = do+  let ss   = map (stabToS . view (_2 . _2)) defs+  (sub,s') <- unifyTypes (s : ss)+  c <- newName "c"+  let vars     = D.changeTVFlags bndrReq $ D.freeVariablesWellScoped [s']+      varNames = map D.tvName vars+      fd   | null vars = []+           | otherwise = [FunDep [c] varNames]+++  classD (cxt[]) className (D.plainTV c:vars) fd+    $ sigD methodName (return (lens'TypeName `conAppsT` [VarT c, s']))+    : concat+      [ [sigD defName (return ty)+        ,valD (varP defName) (normalB body) []+        ] +++        inlinePragma defName+      | (TopName defName, (_, stab, _)) <- defs+      , let body = appsE [varE composeValName, varE methodName, varE defName]+      , let ty   = quantifyType' (Set.fromList (c:varNames))+                                 (stabToContext stab)+                 $ stabToOptic stab `conAppsT`+                       [VarT c, applyTypeSubst sub (stabToA stab)]+      ]+++makeClassyInstance ::+  LensRules ->+  Name ->+  Name ->+  Type {- ^ Outer 's' type -} ->+  [(DefName, (OpticType, OpticStab, [(Name, Int, [(Maybe Name, Int)])]))] ->+  HasFieldClasses Dec+makeClassyInstance rules className methodName s defs = do+  methodss <- traverse (makeFieldOptic rules') defs++  lift $ instanceD (cxt[]) (return instanceHead)+           $ valD (varP methodName) (normalB (varE idValName)) []+           : map return (concat methodss)++  where+  instanceHead = className `conAppsT` (s : map tvbToType vars)+  vars         = D.freeVariablesWellScoped [s]+  rules'       = rules { _generateSigs    = False+                       , _generateClasses = False+                       }++------------------------------------------------------------------------+-- Field class generation+------------------------------------------------------------------------++makeFieldClass :: OpticStab -> Name -> Name -> DecQ+makeFieldClass defType className methodName =+  classD (cxt []) className [D.plainTV s, D.plainTV a] [FunDep [s] [a]]+         [sigD methodName (return methodType)]+  where+  methodType = quantifyType' (Set.fromList [s,a])+                             (stabToContext defType)+             $ stabToOptic defType `conAppsT` [VarT s,VarT a]+  s = mkName "s"+  a = mkName "a"++-- | Build an instance for a field. If the field’s type contains any type+-- families, will produce an equality constraint to avoid a type family+-- application in the instance head.+makeFieldInstance :: OpticStab -> Name -> [DecQ] -> DecQ+makeFieldInstance defType className decs =+  containsTypeFamilies a >>= pickInstanceDec+  where+  s = stabToS defType+  a = stabToA defType++  containsTypeFamilies = go <=< D.resolveTypeSynonyms+    where+    go :: Type -> Q Bool+    go (ConT nm) =+      -- Note that the call to `reify` can fail if `nm` is not yet defined.+      -- (This can actually happen if `nm` is declared in a Template Haskell+      -- quote.) If this fails, there is no way to tell if the type contains+      -- type families, so we recover and conservatively assume that is does not+      -- contain any.+      recover+        (pure False)+        (has (_FamilyI . _1 . _TypeFamilyD) <$> reify nm)+    go ty = or <$> traverse go (ty ^.. plate)++    -- We want to catch type families, but not *data* families. See #799.+    _TypeFamilyD :: Getting Any Dec ()+    _TypeFamilyD = _OpenTypeFamilyD.united <> _ClosedTypeFamilyD.united++  pickInstanceDec hasFamilies+    | hasFamilies = do+        placeholder <- VarT <$> newName "a"+        mkInstanceDec+          [return (D.equalPred placeholder a)]+          [s, placeholder]+    | otherwise = mkInstanceDec [] [s, a]++  mkInstanceDec context headTys =+    instanceD (cxt context) (return (className `conAppsT` headTys)) decs++------------------------------------------------------------------------+-- Optic clause generators+------------------------------------------------------------------------+++makeFieldClauses :: LensRules -> OpticType -> [(Name, Int, [(Maybe Name, Int)])] -> [ClauseQ]+makeFieldClauses rules opticType cons =+  case opticType of++    IsoType    -> [ makeIsoClause conName | (conName, _, _) <- cons ]++    GetterType -> [ makeGetterClause conName fieldCount (snd <$> fields)+                    | (conName, fieldCount, fields) <- cons ]++    LensType   -> [ makeFieldOpticClause conName fieldCount fields irref recSyn+                    | (conName, fieldCount, fields) <- cons ]+      where+      irref = _lazyPatterns rules+           && length cons == 1+      recSyn = _recordSyntax rules && length cons == 1++++-- | Construct an optic clause that returns an unmodified value+-- given a constructor name and the number of fields on that+-- constructor.+makePureClause :: Name -> Int -> ClauseQ+makePureClause conName fieldCount =+  do xs <- newNames "x" fieldCount+     -- clause: _ (Con x1..xn) = pure (Con x1..xn)+     clause [wildP, conP conName (map varP xs)]+            (normalB (appE (varE pureValName) (appsE (conE conName : map varE xs))))+            []+++-- | Construct an optic clause suitable for a Getter or Fold+-- by visited the fields identified by their 0 indexed positions+makeGetterClause :: Name -> Int -> [Int] -> ClauseQ+makeGetterClause conName fieldCount []     = makePureClause conName fieldCount+makeGetterClause conName fieldCount fields =+  do f  <- newName "f"+     xs <- newNames "x" (length fields)+     xs' <-+       case xs of+         (x:xs') -> pure (x :| xs')+         []      -> fail "makeGetterClause: Internal check failed"++     let pats (i:is) (y:ys)+           | i `elem` fields = varP y : pats is ys+           | otherwise = wildP : pats is (y:ys)+         pats is     _  = map (const wildP) is++         (fx :| fxs) = fmap (appE (varE f) . varE) xs'+         body  = foldl (\a b -> appsE [varE apValName, a, b])+                       (appE (varE phantomValName) fx)+                       fxs++     -- clause f (Con x1..xn) = coerce (f x1) <*> ... <*> f xn+     clause [varP f, conP conName (pats [0..fieldCount - 1] xs)]+            (normalB body)+            []++-- | Build a clause that updates the field at the given indexes+-- When irref is 'True' the value with me matched with an irrefutable+-- pattern. This is suitable for Lens and Traversal construction+makeFieldOpticClause :: Name -> Int -> [(Maybe Name, Int)] -> Bool -> Bool -> ClauseQ+makeFieldOpticClause conName fieldCount [] _ _ =+  makePureClause conName fieldCount+makeFieldOpticClause _ _ [(Just fieldName, _)] _ True =+  do f <- newName "f"+     r <- newName "r"+     x <- newName "x"+     let body = appsE [ [| fmap |]+                      , lamE [varP x] (recUpdE (varE r) [(,) fieldName <$> varE x])+                      , varE f `appE` (varE fieldName `appE` varE r)+                      ]+     clause [varP f, varP r] (normalB body) []+makeFieldOpticClause conName fieldCount ((_, field):fieldsWithNames) irref _ =+  do f  <- newName "f"+     xs <- newNames "x" fieldCount+     ys <- newNames "y" (1 + length fieldsWithNames)++     let fields = snd <$> fieldsWithNames+         xs' = foldr (\(i,x) -> set (ix i) x) xs (zip (field:fields) ys)++         mkFx i = appE (varE f) (varE (xs !! i))++         body0 = appsE [ varE fmapValName+                       , lamE (map varP ys) (appsE (conE conName : map varE xs'))+                       , mkFx field+                       ]++         body = foldl (\a b -> appsE [varE apValName, a, mkFx b]) body0 fields++     let wrap = if irref then tildeP else id++     clause [varP f, wrap (conP conName (map varP xs))]+            (normalB body)+            []+++-- | Build a clause that constructs an Iso+makeIsoClause :: Name -> ClauseQ+makeIsoClause conName = clause [] (normalB (appsE [varE isoValName, destruct, construct])) []+  where+  destruct  = do x <- newName "x"+                 lam1E (conP conName [varP x]) (varE x)++  construct = conE conName+++------------------------------------------------------------------------+-- Unification logic+------------------------------------------------------------------------++-- The field-oriented optic generation supports incorporating fields+-- with distinct but unifiable types into a single definition.++++-- | Unify the given list of types, if possible, and return the+-- substitution used to unify the types for unifying the outer+-- type when building a definition's type signature.+unifyTypes :: [Type] -> Q (Map Name Type, Type)+unifyTypes (x:xs) = foldM (uncurry unify1) (Map.empty, x) xs+unifyTypes []     = fail "unifyTypes: Bug: Unexpected empty list"+++-- | Attempt to unify two given types using a running substitution+unify1 :: Map Name Type -> Type -> Type -> Q (Map Name Type, Type)+unify1 sub (VarT x) y+  | Just r <- Map.lookup x sub = unify1 sub r y+unify1 sub x (VarT y)+  | Just r <- Map.lookup y sub = unify1 sub x r+unify1 sub x y+  | x == y = return (sub, x)+unify1 sub (AppT f1 x1) (AppT f2 x2) =+  do (sub1, f) <- unify1 sub  f1 f2+     (sub2, x) <- unify1 sub1 x1 x2+     return (sub2, AppT (applyTypeSubst sub2 f) x)+unify1 sub x (VarT y)+  | elemOf typeVars y (applyTypeSubst sub x) =+      fail "Failed to unify types: occurs check"+  | otherwise = return (Map.insert y x sub, x)+unify1 sub (VarT x) y = unify1 sub y (VarT x)++-- TODO: Unify contexts+unify1 sub (ForallT v1 [] t1) (ForallT v2 [] t2) =+     -- This approach works out because by the time this code runs+     -- all of the type variables have been renamed. No risk of shadowing.+  do (sub1,t) <- unify1 sub t1 t2+     v <- fmap nub (traverse (limitedSubst sub1) (v1++v2))+     return (sub1, ForallT v [] t)++unify1 _ x y = fail ("Failed to unify types: " ++ show (x,y))+++-- | Perform a limited substitution on type variables. This is used+-- when unifying rank-2 fields when trying to achieve a Getter or Fold.+limitedSubst :: Map Name Type -> D.TyVarBndrSpec -> Q D.TyVarBndrSpec+limitedSubst sub tv+  | Just r <- Map.lookup (D.tvName tv) sub =+       case r of+         VarT m -> limitedSubst sub (D.mapTVName (const m) tv)+         _ -> fail "Unable to unify exotic higher-rank type"+  | otherwise = return tv+++-- | Apply a substitution to a type. This is used after unifying+-- the types of the fields in unifyTypes.+applyTypeSubst :: Map Name Type -> Type -> Type+applyTypeSubst sub = rewrite aux+  where+  aux (VarT n) = Map.lookup n sub+  aux _        = Nothing+++------------------------------------------------------------------------+-- Field generation parameters+------------------------------------------------------------------------++-- | Rules to construct lenses for data fields.+data LensRules = LensRules+  { _simpleLenses    :: Bool+  , _generateSigs    :: Bool+  , _generateClasses :: Bool+  , _allowIsos       :: Bool+  , _allowUpdates    :: Bool -- ^ Allow Lens/Traversal (otherwise Getter/Fold)+  , _lazyPatterns    :: Bool+  , _recordSyntax    :: Bool+  , _fieldToDef      :: FieldNamer+       -- ^ Type Name -> Field Names -> Target Field Name -> Definition Names+  , _classyLenses    :: ClassyNamer+       -- type name to class name and top method+  }++-- | The rule to create function names of lenses for data fields.+--+-- Although it's sometimes useful, you won't need the first two+-- arguments most of the time.+type FieldNamer = Name -- ^ Name of the data type that lenses are being generated for.+                  -> [Name] -- ^ Names of all fields (including the field being named) in the data type.+                  -> Name -- ^ Name of the field being named.+                  -> [DefName] -- ^ Name(s) of the lens functions. If empty, no lens is created for that field.++-- | Name to give to generated field optics.+data DefName+  = TopName Name -- ^ Simple top-level definition name+  | MethodName Name Name -- ^ makeFields-style class name and method name+  deriving (Show, Eq, Ord)++-- | The optional rule to create a class and method around a+-- monomorphic data type. If this naming convention is provided, it+-- generates a "classy" lens.+type ClassyNamer = Name -- ^ Name of the data type that lenses are being generated for.+                   -> Maybe (Name, Name) -- ^ Names of the class and the main method it generates, respectively.++-- | Tracks the field class 'Name's that have been created so far. We consult+-- these so that we may avoid creating duplicate classes.++-- See #643 for more information.+type HasFieldClasses = StateT (Set Name) Q++addFieldClassName :: Name -> HasFieldClasses ()+addFieldClassName n = modify $ Set.insert n
+ src/Control/Lens/Internal/Fold.hs view
@@ -0,0 +1,200 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE UndecidableInstances #-}+{-# OPTIONS_GHC -Wno-redundant-constraints #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Fold+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+----------------------------------------------------------------------------+module Control.Lens.Internal.Fold+  (+  -- * Monoids for folding+    Folding(..)+  , Traversed(..)+  , TraversedF(..)+  , Sequenced(..)+  , Leftmost(..), getLeftmost+  , Rightmost(..), getRightmost+  , ReifiedMonoid(..)+  -- * Semigroups for folding+  , NonEmptyDList(..)+  ) where++import Prelude ()++import Control.Lens.Internal.Getter+import Control.Lens.Internal.Prelude+import Data.Functor.Bind+import Data.Maybe (fromMaybe)+import Data.Reflection++import qualified Data.List.NonEmpty as NonEmpty++------------------------------------------------------------------------------+-- Folding+------------------------------------------------------------------------------++-- | A 'Monoid' for a 'Contravariant' 'Applicative'.+newtype Folding f a = Folding { getFolding :: f a }++instance (Contravariant f, Applicative f) => Semigroup (Folding f a) where+  Folding fr <> Folding fs = Folding (fr *> fs)+  {-# INLINE (<>) #-}++instance (Contravariant f, Applicative f) => Monoid (Folding f a) where+  mempty = Folding noEffect+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  Folding fr `mappend` Folding fs = Folding (fr *> fs)+  {-# INLINE mappend #-}+#endif++------------------------------------------------------------------------------+-- Traversed+------------------------------------------------------------------------------++-- | Used internally by 'Control.Lens.Traversal.traverseOf_' and the like.+--+-- The argument 'a' of the result should not be used!+newtype Traversed a f = Traversed { getTraversed :: f a }++-- See 4.16 Changelog entry for the explanation of "why not Apply f =>"?+instance Applicative f => Semigroup (Traversed a f) where+  Traversed ma <> Traversed mb = Traversed (ma *> mb)+  {-# INLINE (<>) #-}++instance Applicative f => Monoid (Traversed a f) where+  mempty = Traversed (pure (error "Traversed: value used"))+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  Traversed ma `mappend` Traversed mb = Traversed (ma *> mb)+  {-# INLINE mappend #-}+#endif++------------------------------------------------------------------------------+-- TraversedF+------------------------------------------------------------------------------++-- | Used internally by 'Control.Lens.Fold.traverse1Of_' and the like.+--+-- @since 4.16+newtype TraversedF a f = TraversedF { getTraversedF :: f a }++instance Apply f => Semigroup (TraversedF a f) where+  TraversedF ma <> TraversedF mb = TraversedF (ma .> mb)+  {-# INLINE (<>) #-}++instance (Apply f, Applicative f) => Monoid (TraversedF a f) where+  mempty = TraversedF (pure (error "TraversedF: value used"))+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  TraversedF ma `mappend` TraversedF mb = TraversedF (ma *> mb)+  {-# INLINE mappend #-}+#endif++------------------------------------------------------------------------------+-- Sequenced+------------------------------------------------------------------------------++-- | Used internally by 'Control.Lens.Traversal.mapM_' and the like.+--+-- The argument 'a' of the result should not be used!+--+-- See 4.16 Changelog entry for the explanation of "why not Apply f =>"?+newtype Sequenced a m = Sequenced { getSequenced :: m a }++instance Monad m => Semigroup (Sequenced a m) where+  Sequenced ma <> Sequenced mb = Sequenced (ma >> mb)+  {-# INLINE (<>) #-}++instance Monad m => Monoid (Sequenced a m) where+  mempty = Sequenced (return (error "Sequenced: value used"))+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  Sequenced ma `mappend` Sequenced mb = Sequenced (ma >> mb)+  {-# INLINE mappend #-}+#endif++------------------------------------------------------------------------------+-- NonEmptyDList+------------------------------------------------------------------------------++newtype NonEmptyDList a+  = NonEmptyDList { getNonEmptyDList :: [a] -> NonEmpty.NonEmpty a }++instance Semigroup (NonEmptyDList a) where+  NonEmptyDList f <> NonEmptyDList g = NonEmptyDList (f . NonEmpty.toList . g)++------------------------------------------------------------------------------+-- Leftmost and Rightmost+------------------------------------------------------------------------------++-- | Used for 'Control.Lens.Fold.firstOf'.+data Leftmost a = LPure | LLeaf a | LStep (Leftmost a)++instance Semigroup (Leftmost a) where+  x <> y = LStep $ case x of+    LPure    -> y+    LLeaf _  -> x+    LStep x' -> case y of+      -- The last two cases make firstOf produce a Just as soon as any element+      -- is encountered, and possibly serve as a micro-optimisation; this+      -- behaviour can be disabled by replacing them with _ -> x <> y'.+      -- Note that this means that firstOf (backwards folded) [1..] is Just _|_.+      LPure    -> x'+      LLeaf a  -> LLeaf $ fromMaybe a (getLeftmost x')+      LStep y' -> mappend x' y'++instance Monoid (Leftmost a) where+  mempty = LPure+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  mappend = (<>)+  {-# INLINE mappend #-}+#endif++-- | Extract the 'Leftmost' element. This will fairly eagerly determine that it can return 'Just'+-- the moment it sees any element at all.+getLeftmost :: Leftmost a -> Maybe a+getLeftmost LPure = Nothing+getLeftmost (LLeaf a) = Just a+getLeftmost (LStep x) = getLeftmost x++-- | Used for 'Control.Lens.Fold.lastOf'.+data Rightmost a = RPure | RLeaf a | RStep (Rightmost a)++instance Semigroup (Rightmost a) where+  x <> y = RStep $ case y of+    RPure    -> x+    RLeaf _  -> y+    RStep y' -> case x of+      -- The last two cases make lastOf produce a Just as soon as any element+      -- is encountered, and possibly serve as a micro-optimisation; this+      -- behaviour can be disabled by replacing them with _ -> x <> y'.+      -- Note that this means that lastOf folded [1..] is Just _|_.+      RPure    -> y'+      RLeaf a  -> RLeaf $ fromMaybe a (getRightmost y')+      RStep x' -> mappend x' y'++instance Monoid (Rightmost a) where+  mempty = RPure+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  mappend = (<>)+  {-# INLINE mappend #-}+#endif++-- | Extract the 'Rightmost' element. This will fairly eagerly determine that it can return 'Just'+-- the moment it sees any element at all.+getRightmost :: Rightmost a -> Maybe a+getRightmost RPure = Nothing+getRightmost (RLeaf a) = Just a+getRightmost (RStep x) = getRightmost x
+ src/Control/Lens/Internal/Getter.hs view
@@ -0,0 +1,115 @@+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Getter+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  non-portable+--+----------------------------------------------------------------------------+module Control.Lens.Internal.Getter+  ( noEffect+  , AlongsideLeft(..)+  , AlongsideRight(..)+  ) where++import Prelude ()++import Control.Lens.Internal.Prelude+import Data.Bifoldable+import Data.Bifunctor+import Data.Bitraversable+import Data.Semigroup.Foldable+import Data.Semigroup.Traversable++-- | The 'mempty' equivalent for a 'Contravariant' 'Applicative' 'Functor'.+noEffect :: (Contravariant f, Applicative f) => f a+noEffect = phantom $ pure ()+{-# INLINE noEffect #-}++newtype AlongsideLeft f b a = AlongsideLeft { getAlongsideLeft :: f (a, b) }++deriving instance Show (f (a, b)) => Show (AlongsideLeft f b a)+deriving instance Read (f (a, b)) => Read (AlongsideLeft f b a)++instance Functor f => Functor (AlongsideLeft f b) where+  fmap f = AlongsideLeft . fmap (first f) . getAlongsideLeft+  {-# INLINE fmap #-}++instance Contravariant f => Contravariant (AlongsideLeft f b) where+  contramap f = AlongsideLeft . contramap (first f) . getAlongsideLeft+  {-# INLINE contramap #-}++instance Foldable f => Foldable (AlongsideLeft f b) where+  foldMap f = foldMap (f . fst) . getAlongsideLeft+  {-# INLINE foldMap #-}++instance Traversable f => Traversable (AlongsideLeft f b) where+  traverse f (AlongsideLeft as) = AlongsideLeft <$> traverse (bitraverse f pure) as+  {-# INLINE traverse #-}++instance Foldable1 f => Foldable1 (AlongsideLeft f b) where+  foldMap1 f = foldMap1 (f . fst) . getAlongsideLeft+  {-# INLINE foldMap1 #-}++instance Traversable1 f => Traversable1 (AlongsideLeft f b) where+  traverse1 f (AlongsideLeft as) = AlongsideLeft <$> traverse1 (\(a,b) -> flip (,) b <$> f a) as+  {-# INLINE traverse1 #-}++instance Functor f => Bifunctor (AlongsideLeft f) where+  bimap f g = AlongsideLeft . fmap (bimap g f) . getAlongsideLeft+  {-# INLINE bimap #-}++instance Foldable f => Bifoldable (AlongsideLeft f) where+  bifoldMap f g = foldMap (bifoldMap g f) . getAlongsideLeft+  {-# INLINE bifoldMap #-}++instance Traversable f => Bitraversable (AlongsideLeft f) where+  bitraverse f g (AlongsideLeft as) = AlongsideLeft <$> traverse (bitraverse g f) as+  {-# INLINE bitraverse #-}++newtype AlongsideRight f a b = AlongsideRight { getAlongsideRight :: f (a, b) }++deriving instance Show (f (a, b)) => Show (AlongsideRight f a b)+deriving instance Read (f (a, b)) => Read (AlongsideRight f a b)++instance Functor f => Functor (AlongsideRight f a) where+  fmap f (AlongsideRight x) = AlongsideRight (fmap (second f) x)+  {-# INLINE fmap #-}++instance Contravariant f => Contravariant (AlongsideRight f a) where+  contramap f (AlongsideRight x) = AlongsideRight (contramap (second f) x)+  {-# INLINE contramap #-}++instance Foldable f => Foldable (AlongsideRight f a) where+  foldMap f = foldMap (f . snd) . getAlongsideRight+  {-# INLINE foldMap #-}++instance Traversable f => Traversable (AlongsideRight f a) where+  traverse f (AlongsideRight as) = AlongsideRight <$> traverse (bitraverse pure f) as+  {-# INLINE traverse #-}++instance Foldable1 f => Foldable1 (AlongsideRight f a) where+  foldMap1 f = foldMap1 (f . snd) . getAlongsideRight+  {-# INLINE foldMap1 #-}++instance Traversable1 f => Traversable1 (AlongsideRight f a) where+  traverse1 f (AlongsideRight as) = AlongsideRight <$> traverse1 (\(a,b) -> (,) a <$> f b) as+  {-# INLINE traverse1 #-}++instance Functor f => Bifunctor (AlongsideRight f) where+  bimap f g = AlongsideRight . fmap (bimap f g) . getAlongsideRight+  {-# INLINE bimap #-}++instance Foldable f => Bifoldable (AlongsideRight f) where+  bifoldMap f g = foldMap (bifoldMap f g) . getAlongsideRight+  {-# INLINE bifoldMap #-}++instance Traversable f => Bitraversable (AlongsideRight f) where+  bitraverse f g (AlongsideRight as) = AlongsideRight <$> traverse (bitraverse f g) as+  {-# INLINE bitraverse #-}
+ src/Control/Lens/Internal/Indexed.hs view
@@ -0,0 +1,383 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE Trustworthy #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Indexed+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-- Internal implementation details for 'Indexed' lens-likes+----------------------------------------------------------------------------+module Control.Lens.Internal.Indexed+  (+  -- * An Indexed Profunctor+    Indexed(..)+  -- * Classes+  , Conjoined(..)+  , Indexable(..)+  -- * Indexing+  , Indexing(..)+  , indexing+  -- * 64-bit Indexing+  , Indexing64(..)+  , indexing64+  -- * Converting to Folds+  , withIndex+  , asIndex+  ) where++import Prelude ()++import Control.Arrow as Arrow+import qualified Control.Category as C+import Control.Comonad+import Control.Lens.Internal.Prelude+import Control.Lens.Internal.Instances ()+import Control.Monad.Fix+import Data.Distributive+import Data.Functor.Bind+import Data.Int+import Data.Profunctor.Closed+import Data.Profunctor.Rep++-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import Numeric.Lens+-- >>> import Data.Semigroup (Semigroup (..))+--+------------------------------------------------------------------------------+-- Conjoined+------------------------------------------------------------------------------++-- | This is a 'Profunctor' that is both 'Corepresentable' by @f@ and 'Representable' by @g@ such+-- that @f@ is left adjoint to @g@. From this you can derive a lot of structure due+-- to the preservation of limits and colimits.+class+  ( Choice p, Corepresentable p, Comonad (Corep p), Traversable (Corep p)+  , Strong p, Representable p, Monad (Rep p), MonadFix (Rep p), Distributive (Rep p)+  , Costrong p, ArrowLoop p, ArrowApply p, ArrowChoice p, Closed p+  ) => Conjoined p where++  -- | 'Conjoined' is strong enough to let us distribute every 'Conjoined'+  -- 'Profunctor' over every Haskell 'Functor'. This is effectively a+  -- generalization of 'fmap'.+  distrib :: Functor f => p a b -> p (f a) (f b)+  distrib = tabulate . collect . sieve+  {-# INLINE distrib #-}++  -- | This permits us to make a decision at an outermost point about whether or not we use an index.+  --+  -- Ideally any use of this function should be done in such a way so that you compute the same answer,+  -- but this cannot be enforced at the type level.+  conjoined :: ((p ~ (->)) => q (a -> b) r) -> q (p a b) r -> q (p a b) r+  conjoined _ r = r+  {-# INLINE conjoined #-}++instance Conjoined (->) where+  distrib = fmap+  {-# INLINE distrib #-}+  conjoined l _ = l+  {-# INLINE conjoined #-}++----------------------------------------------------------------------------+-- Indexable+----------------------------------------------------------------------------++-- | This class permits overloading of function application for things that+-- also admit a notion of a key or index.+class Conjoined p => Indexable i p where+  -- | Build a function from an 'indexed' function.+  indexed :: p a b -> i -> a -> b++instance Indexable i (->) where+  indexed = const+  {-# INLINE indexed #-}++-----------------------------------------------------------------------------+-- Indexed Internals+-----------------------------------------------------------------------------++-- | A function with access to a index. This constructor may be useful when you need to store+-- an 'Indexable' in a container to avoid @ImpredicativeTypes@.+--+-- @index :: Indexed i a b -> i -> a -> b@+newtype Indexed i a b = Indexed { runIndexed :: i -> a -> b }++instance Functor (Indexed i a) where+  fmap g (Indexed f) = Indexed $ \i a -> g (f i a)+  {-# INLINE fmap #-}++instance Apply (Indexed i a) where+  Indexed f <.> Indexed g = Indexed $ \i a -> f i a (g i a)+  {-# INLINE (<.>) #-}++instance Applicative (Indexed i a) where+  pure b = Indexed $ \_ _ -> b+  {-# INLINE pure #-}+  Indexed f <*> Indexed g = Indexed $ \i a -> f i a (g i a)+  {-# INLINE (<*>) #-}++instance Bind (Indexed i a) where+  Indexed f >>- k = Indexed $ \i a -> runIndexed (k (f i a)) i a+  {-# INLINE (>>-) #-}++instance Monad (Indexed i a) where+  return = pure+  {-# INLINE return #-}+  Indexed f >>= k = Indexed $ \i a -> runIndexed (k (f i a)) i a+  {-# INLINE (>>=) #-}++instance MonadFix (Indexed i a) where+  mfix f = Indexed $ \ i a -> let o = runIndexed (f o) i a in o+  {-# INLINE mfix #-}++instance Profunctor (Indexed i) where+  dimap ab cd ibc = Indexed $ \i -> cd . runIndexed ibc i . ab+  {-# INLINE dimap #-}+  lmap ab ibc = Indexed $ \i -> runIndexed ibc i . ab+  {-# INLINE lmap #-}+  rmap bc iab = Indexed $ \i -> bc . runIndexed iab i+  {-# INLINE rmap #-}+  (.#) ibc _ = coerce ibc+  {-# INLINE (.#) #-}+  (#.) _ = coerce+  {-# INLINE (#.) #-}++instance Closed (Indexed i) where+  closed (Indexed iab) = Indexed $ \i xa x -> iab i (xa x)++instance Costrong (Indexed i) where+  unfirst (Indexed iadbd) = Indexed $ \i a -> let+      (b, d) = iadbd i (a, d)+    in b++instance Sieve (Indexed i) ((->) i) where+  sieve = flip . runIndexed+  {-# INLINE sieve #-}++instance Representable (Indexed i) where+  type Rep (Indexed i) = (->) i+  tabulate = Indexed . flip+  {-# INLINE tabulate #-}++instance Cosieve (Indexed i) ((,) i) where+  cosieve = uncurry . runIndexed+  {-# INLINE cosieve #-}++instance Corepresentable (Indexed i) where+  type Corep (Indexed i) = (,) i+  cotabulate = Indexed . curry+  {-# INLINE cotabulate #-}++instance Choice (Indexed i) where+  right' = right+  {-# INLINE right' #-}++instance Strong (Indexed i) where+  second' = second+  {-# INLINE second' #-}++instance C.Category (Indexed i) where+  id = Indexed (const id)+  {-# INLINE id #-}+  Indexed f . Indexed g = Indexed $ \i -> f i . g i+  {-# INLINE (.) #-}++instance Arrow (Indexed i) where+  arr f = Indexed (\_ -> f)+  {-# INLINE arr #-}+  first f = Indexed (Arrow.first . runIndexed f)+  {-# INLINE first #-}+  second f = Indexed (Arrow.second . runIndexed f)+  {-# INLINE second #-}+  Indexed f *** Indexed g = Indexed $ \i -> f i *** g i+  {-# INLINE (***) #-}+  Indexed f &&& Indexed g = Indexed $ \i -> f i &&& g i+  {-# INLINE (&&&) #-}++instance ArrowChoice (Indexed i) where+  left f = Indexed (left . runIndexed f)+  {-# INLINE left #-}+  right f = Indexed (right . runIndexed f)+  {-# INLINE right #-}+  Indexed f +++ Indexed g = Indexed $ \i -> f i +++ g i+  {-# INLINE (+++)  #-}+  Indexed f ||| Indexed g = Indexed $ \i -> f i ||| g i+  {-# INLINE (|||) #-}++instance ArrowApply (Indexed i) where+  app = Indexed $ \ i (f, b) -> runIndexed f i b+  {-# INLINE app #-}++instance ArrowLoop (Indexed i) where+  loop (Indexed f) = Indexed $ \i b -> let (c,d) = f i (b, d) in c+  {-# INLINE loop #-}++instance Conjoined (Indexed i) where+  distrib (Indexed iab) = Indexed $ \i fa -> iab i <$> fa+  {-# INLINE distrib #-}++instance i ~ j => Indexable i (Indexed j) where+  indexed = runIndexed+  {-# INLINE indexed #-}++------------------------------------------------------------------------------+-- Indexing+------------------------------------------------------------------------------++-- | 'Applicative' composition of @'Control.Monad.Trans.State.Lazy.State' 'Int'@ with a 'Functor', used+-- by 'Control.Lens.Indexed.indexed'.+newtype Indexing f a = Indexing { runIndexing :: Int -> (Int, f a) }++instance Functor f => Functor (Indexing f) where+  fmap f (Indexing m) = Indexing $ \i -> case m i of+    (j, x) -> (j, fmap f x)+  {-# INLINE fmap #-}++instance Apply f => Apply (Indexing f) where+  Indexing mf <.> Indexing ma = Indexing $ \i -> case mf i of+    (j, ff) -> case ma j of+       ~(k, fa) -> (k, ff <.> fa)+  {-# INLINE (<.>) #-}++instance Applicative f => Applicative (Indexing f) where+  pure x = Indexing $ \i -> (i, pure x)+  {-# INLINE pure #-}+  Indexing mf <*> Indexing ma = Indexing $ \i -> case mf i of+    (j, ff) -> case ma j of+       ~(k, fa) -> (k, ff <*> fa)+  {-# INLINE (<*>) #-}++instance Contravariant f => Contravariant (Indexing f) where+  contramap f (Indexing m) = Indexing $ \i -> case m i of+    (j, ff) -> (j, contramap f ff)+  {-# INLINE contramap #-}++instance Semigroup (f a) => Semigroup (Indexing f a) where+    Indexing mx <> Indexing my = Indexing $ \i -> case mx i of+      (j, x) -> case my j of+         ~(k, y) -> (k, x <> y)+    {-# INLINE (<>) #-}++-- |+--+-- >>> "cat" ^@.. (folded <> folded)+-- [(0,'c'),(1,'a'),(2,'t'),(0,'c'),(1,'a'),(2,'t')]+--+-- >>> "cat" ^@.. indexing (folded <> folded)+-- [(0,'c'),(1,'a'),(2,'t'),(3,'c'),(4,'a'),(5,'t')]+instance Monoid (f a) => Monoid (Indexing f a) where+    mempty = Indexing $ \i -> (i, mempty)+    {-# INLINE mempty #-}++#if !(MIN_VERSION_base(4,11,0))+    mappend (Indexing mx) (Indexing my) = Indexing $ \i -> case mx i of+      (j, x) -> case my j of+         ~(k, y) -> (k, mappend x y)+    {-# INLINE mappend #-}+#endif++-- | Transform a 'Control.Lens.Traversal.Traversal' into an 'Control.Lens.Traversal.IndexedTraversal' or+-- a 'Control.Lens.Fold.Fold' into an 'Control.Lens.Fold.IndexedFold', etc.+--+-- @+-- 'indexing' :: 'Control.Lens.Type.Traversal' s t a b -> 'Control.Lens.Type.IndexedTraversal' 'Int' s t a b+-- 'indexing' :: 'Control.Lens.Type.Prism' s t a b     -> 'Control.Lens.Type.IndexedTraversal' 'Int' s t a b+-- 'indexing' :: 'Control.Lens.Type.Lens' s t a b      -> 'Control.Lens.Type.IndexedLens' 'Int'  s t a b+-- 'indexing' :: 'Control.Lens.Type.Iso' s t a b       -> 'Control.Lens.Type.IndexedLens' 'Int' s t a b+-- 'indexing' :: 'Control.Lens.Type.Fold' s a          -> 'Control.Lens.Type.IndexedFold' 'Int' s a+-- 'indexing' :: 'Control.Lens.Type.Getter' s a        -> 'Control.Lens.Type.IndexedGetter' 'Int' s a+-- @+--+-- @'indexing' :: 'Indexable' 'Int' p => 'Control.Lens.Type.LensLike' ('Indexing' f) s t a b -> 'Control.Lens.Type.Over' p f s t a b@+indexing :: Indexable Int p => ((a -> Indexing f b) -> s -> Indexing f t) -> p a (f b) -> s -> f t+indexing l iafb s = snd $ runIndexing (l (\a -> Indexing (\i -> i `seq` (i + 1, indexed iafb i a))) s) 0+{-# INLINE indexing #-}++------------------------------------------------------------------------------+-- Indexing64+------------------------------------------------------------------------------++-- | 'Applicative' composition of @'Control.Monad.Trans.State.Lazy.State' 'Int64'@ with a 'Functor', used+-- by 'Control.Lens.Indexed.indexed64'.+newtype Indexing64 f a = Indexing64 { runIndexing64 :: Int64 -> (Int64, f a) }++instance Functor f => Functor (Indexing64 f) where+  fmap f (Indexing64 m) = Indexing64 $ \i -> case m i of+    (j, x) -> (j, fmap f x)+  {-# INLINE fmap #-}++instance Apply f => Apply (Indexing64 f) where+  Indexing64 mf <.> Indexing64 ma = Indexing64 $ \i -> case mf i of+    (j, ff) -> case ma j of+       ~(k, fa) -> (k, ff <.> fa)+  {-# INLINE (<.>) #-}++instance Applicative f => Applicative (Indexing64 f) where+  pure x = Indexing64 $ \i -> (i, pure x)+  {-# INLINE pure #-}+  Indexing64 mf <*> Indexing64 ma = Indexing64 $ \i -> case mf i of+    (j, ff) -> case ma j of+       ~(k, fa) -> (k, ff <*> fa)+  {-# INLINE (<*>) #-}++instance Contravariant f => Contravariant (Indexing64 f) where+  contramap f (Indexing64 m) = Indexing64 $ \i -> case m i of+    (j, ff) -> (j, contramap f ff)+  {-# INLINE contramap #-}++-- | Transform a 'Control.Lens.Traversal.Traversal' into an 'Control.Lens.Traversal.IndexedTraversal' or+-- a 'Control.Lens.Fold.Fold' into an 'Control.Lens.Fold.IndexedFold', etc.+--+-- This combinator is like 'indexing' except that it handles large traversals and folds gracefully.+--+-- @+-- 'indexing64' :: 'Control.Lens.Type.Traversal' s t a b -> 'Control.Lens.Type.IndexedTraversal' 'Int64' s t a b+-- 'indexing64' :: 'Control.Lens.Type.Prism' s t a b     -> 'Control.Lens.Type.IndexedTraversal' 'Int64' s t a b+-- 'indexing64' :: 'Control.Lens.Type.Lens' s t a b      -> 'Control.Lens.Type.IndexedLens' 'Int64' s t a b+-- 'indexing64' :: 'Control.Lens.Type.Iso' s t a b       -> 'Control.Lens.Type.IndexedLens' 'Int64' s t a b+-- 'indexing64' :: 'Control.Lens.Type.Fold' s a          -> 'Control.Lens.Type.IndexedFold' 'Int64' s a+-- 'indexing64' :: 'Control.Lens.Type.Getter' s a        -> 'Control.Lens.Type.IndexedGetter' 'Int64' s a+-- @+--+-- @'indexing64' :: 'Indexable' 'Int64' p => 'Control.Lens.Type.LensLike' ('Indexing64' f) s t a b -> 'Control.Lens.Type.Over' p f s t a b@+indexing64 :: Indexable Int64 p => ((a -> Indexing64 f b) -> s -> Indexing64 f t) -> p a (f b) -> s -> f t+indexing64 l iafb s = snd $ runIndexing64 (l (\a -> Indexing64 (\i -> i `seq` (i + 1, indexed iafb i a))) s) 0+{-# INLINE indexing64 #-}++-------------------------------------------------------------------------------+-- Converting to Folds+-------------------------------------------------------------------------------++-- | Fold a container with indices returning both the indices and the values.+--+-- The result is only valid to compose in a 'Traversal', if you don't edit the+-- index as edits to the index have no effect.+--+-- >>> [10, 20, 30] ^.. ifolded . withIndex+-- [(0,10),(1,20),(2,30)]+--+-- >>> [10, 20, 30] ^.. ifolded . withIndex . alongside negated (re _Show)+-- [(0,"10"),(-1,"20"),(-2,"30")]+--+withIndex :: (Indexable i p, Functor f) => p (i, s) (f (j, t)) -> Indexed i s (f t)+withIndex f = Indexed $ \i a -> snd <$> indexed f i (i, a)+{-# INLINE withIndex #-}++-- | When composed with an 'IndexedFold' or 'IndexedTraversal' this yields an+-- ('Indexed') 'Fold' of the indices.+asIndex :: (Indexable i p, Contravariant f, Functor f) => p i (f i) -> Indexed i s (f s)+asIndex f = Indexed $ \i _ -> phantom (indexed f i i)+{-# INLINE asIndex #-}
+ src/Control/Lens/Internal/Instances.hs view
@@ -0,0 +1,16 @@+-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Instances+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-- This module includes orphan instances for @(,)@, 'Either' and 'Const' that+-- should be supplied by base. These have moved to @semigroupoids@ as of 4.2.+----------------------------------------------------------------------------+module Control.Lens.Internal.Instances () where++import Data.Orphans ()+import Data.Traversable.Instances ()
+ src/Control/Lens/Internal/Iso.hs view
@@ -0,0 +1,110 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE ScopedTypeVariables #-}+#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-}+#endif+-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Iso+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+----------------------------------------------------------------------------+module Control.Lens.Internal.Iso+  ( Exchange(..)+  , Reversing(..)+  ) where++import Data.Profunctor+import Data.Profunctor.Unsafe++import qualified Data.ByteString       as StrictB+import qualified Data.ByteString.Lazy  as LazyB+import Data.Coerce+import qualified Data.List.NonEmpty    as NonEmpty+import qualified Data.Text             as StrictT+import qualified Data.Text.Lazy        as LazyT+import qualified Data.Vector           as Vector+import qualified Data.Vector.Primitive as Prim+import Data.Vector.Primitive (Prim)+import qualified Data.Vector.Storable  as Storable+import qualified Data.Vector.Unboxed   as Unbox+import Data.Vector.Unboxed (Unbox)+#if MIN_VERSION_vector(0,13,2)+import qualified Data.Vector.Strict as VectorStrict+#endif+import qualified Data.Sequence         as Seq+import Data.Sequence (Seq)+import Foreign.Storable (Storable)++------------------------------------------------------------------------------+-- Isomorphism: Exchange+------------------------------------------------------------------------------++-- | This is used internally by the 'Control.Lens.Iso.Iso' code to provide+-- efficient access to the two functions that make up an isomorphism.+data Exchange a b s t = Exchange (s -> a) (b -> t)++instance Functor (Exchange a b s) where+  fmap f (Exchange sa bt) = Exchange sa (f . bt)+  {-# INLINE fmap #-}++instance Profunctor (Exchange a b) where+  dimap f g (Exchange sa bt) = Exchange (sa . f) (g . bt)+  {-# INLINE dimap #-}+  lmap f (Exchange sa bt) = Exchange (sa . f) bt+  {-# INLINE lmap #-}+  rmap f (Exchange sa bt) = Exchange sa (f . bt)+  {-# INLINE rmap #-}+  (#.) _ = coerce+  {-# INLINE (#.) #-}+  (.#) p _ = coerce p++------------------------------------------------------------------------------+-- Reversible+------------------------------------------------------------------------------++-- | This class provides a generalized notion of list reversal extended to other containers.+class Reversing t where+  reversing :: t -> t++instance Reversing [a] where+  reversing = Prelude.reverse++instance Reversing (NonEmpty.NonEmpty a) where+  reversing = NonEmpty.reverse++instance Reversing StrictB.ByteString where+  reversing = StrictB.reverse++instance Reversing LazyB.ByteString where+  reversing = LazyB.reverse++instance Reversing StrictT.Text where+  reversing = StrictT.reverse++instance Reversing LazyT.Text where+  reversing = LazyT.reverse++instance Reversing (Vector.Vector a) where+  reversing = Vector.reverse++instance Reversing (Seq a) where+  reversing = Seq.reverse++instance Prim a => Reversing (Prim.Vector a) where+  reversing = Prim.reverse++instance Unbox a => Reversing (Unbox.Vector a) where+  reversing = Unbox.reverse++instance Storable a => Reversing (Storable.Vector a) where+  reversing = Storable.reverse++#if MIN_VERSION_vector(0,13,2)+instance Reversing (VectorStrict.Vector a) where+  reversing = VectorStrict.reverse+#endif
+ src/Control/Lens/Internal/Level.hs view
@@ -0,0 +1,183 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Level+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-- This module provides implementation details of the combinators in+-- "Control.Lens.Level", which provides for the breadth-first 'Control.Lens.Traversal.Traversal' of+-- an arbitrary 'Control.Lens.Traversal.Traversal'.+----------------------------------------------------------------------------+module Control.Lens.Internal.Level+  (+  -- * Levels+    Level(..)+  , Deepening(..), deepening+  , Flows(..)+  ) where++import Prelude ()++import Control.Lens.Internal.Prelude+import Data.Functor.Apply+import Data.Functor.WithIndex+import Data.Foldable.WithIndex+import Data.Traversable.WithIndex++------------------------------------------------------------------------------+-- Levels+------------------------------------------------------------------------------++-- | This data type represents a path-compressed copy of one level of a source+-- data structure. We can safely use path-compression because we know the depth+-- of the tree.+--+-- Path compression is performed by viewing a 'Level' as a PATRICIA trie of the+-- paths into the structure to leaves at a given depth, similar in many ways+-- to a 'Data.IntMap.IntMap', but unlike a regular PATRICIA trie we do not need+-- to store the mask bits merely the depth of the fork.+--+-- One invariant of this structure is that underneath a 'Two' node you will not+-- find any 'Zero' nodes, so 'Zero' can only occur at the root.+data Level i a+  = Two {-# UNPACK #-} !Word !(Level i a) !(Level i a)+  | One i a+  | Zero+  deriving (Eq,Ord,Show,Read)++-- | Append a pair of 'Level' values to get a new 'Level' with path compression.+--+-- As the 'Level' type is user-visible, we do not expose this as an illegal+-- 'Semigroup' instance, and just use it directly in 'Deepening' as needed.+lappend :: Level i a -> Level i a -> Level i a+lappend Zero        Zero        = Zero+lappend Zero        r@One{}     = r+lappend l@One{}     Zero        = l+lappend Zero        (Two n l r) = Two (n + 1) l r+lappend (Two n l r) Zero        = Two (n + 1) l r+lappend l           r           = Two 0 l r+{-# INLINE lappend #-}++instance Functor (Level i) where+  fmap f = go where+    go (Two n l r) = Two n (go l) (go r)+    go (One i a)   = One i (f a)+    go Zero        = Zero+  {-# INLINE fmap #-}++instance Foldable (Level i) where+  foldMap f = go where+    go (Two _ l r) = go l `mappend` go r+    go (One _ a) = f a+    go Zero = mempty+  {-# INLINE foldMap #-}++instance Traversable (Level i) where+  traverse f = go where+    go (Two n l r) = Two n <$> go l <*> go r+    go (One i a) = One i <$> f a+    go Zero = pure Zero+  {-# INLINE traverse #-}++instance FunctorWithIndex i (Level i) where+  imap f = go where+    go (Two n l r) = Two n (go l) (go r)+    go (One i a)   = One i (f i a)+    go Zero        = Zero+  {-# INLINE imap #-}++instance FoldableWithIndex i (Level i) where+  ifoldMap f = go where+    go (Two _ l r) = go l `mappend` go r+    go (One i a)   = f i a+    go Zero        = mempty+  {-# INLINE ifoldMap #-}++instance TraversableWithIndex i (Level i) where+  itraverse f = go where+    go (Two n l r) = Two n <$> go l <*> go r+    go (One i a)   = One i <$> f i a+    go Zero        = pure Zero+  {-# INLINE itraverse #-}++------------------------------------------------------------------------------+-- Generating Levels+------------------------------------------------------------------------------++-- | This is an illegal 'Monoid' used to construct a single 'Level'.+newtype Deepening i a = Deepening { runDeepening :: forall r. Int -> (Level i a -> Bool -> r) -> r }++instance Semigroup (Deepening i a) where+  Deepening l <> Deepening r = Deepening $ \ n k -> case n of+    0 -> k Zero True+    _ -> let n' = n - 1 in l n' $ \x a -> r n' $ \y b -> k (lappend x y) (a || b)+  {-# INLINE (<>) #-}++-- | This is an illegal 'Monoid'.+instance Monoid (Deepening i a) where+  mempty = Deepening $ \ _ k -> k Zero False+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  mappend (Deepening l) (Deepening r) = Deepening $ \ n k -> case n of+    0 -> k Zero True+    _ -> let n' = n - 1 in l n' $ \x a -> r n' $ \y b -> k (lappend x y) (a || b)+  {-# INLINE mappend #-}+#endif++-- | Generate the leaf of a given 'Deepening' based on whether or not we're at the correct depth.+deepening :: i -> a -> Deepening i a+deepening i a = Deepening $ \n k -> k (if n == 0 then One i a else Zero) False+{-# INLINE deepening #-}++------------------------------------------------------------------------------+-- Reassembling Levels+------------------------------------------------------------------------------++-- | This is an illegal 'Applicative' used to replace the contents of a list of consecutive 'Level' values+-- representing each layer of a structure into the original shape that they were derived from.+--+-- Attempting to 'Flow' something back into a shape other than the one it was taken from will fail.+newtype Flows i b a = Flows { runFlows :: [Level i b] -> a }++instance Functor (Flows i b) where+  fmap f (Flows g) = Flows (f . g)+  {-# INLINE fmap #-}++-- | Walk down one constructor in a 'Level', veering left.+triml :: Level i b -> Level i b+triml (Two 0 l _) = l+triml (Two n l r) = Two (n - 1) l r+triml x           = x+{-# INLINE triml #-}++-- | Walk down one constructor in a 'Level', veering right.+trimr :: Level i b -> Level i b+trimr (Two 0 _ r) = r+trimr (Two n l r) = Two (n - 1) l r+trimr x           = x+{-# INLINE trimr #-}++instance Apply (Flows i b) where+  Flows mf <.> Flows ma = Flows $ \ xss -> case xss of+    []             -> mf [] (ma [])+    (_:xs)         -> mf (triml <$> xs) $ ma (trimr <$> xs)+  {-# INLINE (<.>) #-}++-- | This is an illegal 'Applicative'.+instance Applicative (Flows i b) where+  pure a = Flows (const a)+  {-# INLINE pure #-}+  Flows mf <*> Flows ma = Flows $ \ xss -> case xss of+    []             -> mf [] (ma [])+    (_:xs)         -> mf (triml <$> xs) $ ma (trimr <$> xs)+  {-# INLINE (<*>) #-}
+ src/Control/Lens/Internal/List.hs view
@@ -0,0 +1,73 @@+{-# LANGUAGE CPP #-}+-------------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.List+-- Copyright   :  (C) 2014-2016 Edward Kmett and Eric Mertens+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  non-portable+--+-- This module provides utility functions on lists used by the library+-- implementation.+-------------------------------------------------------------------------------+module Control.Lens.Internal.List+  ( ordinalNub+  , stripSuffix+  ) where++import Control.Monad (guard)+import Data.IntSet (IntSet)+import qualified Data.IntSet as IntSet++--- $setup+--- >>> :set -XNoOverloadedStrings+--- >>> import Control.Lens.Internal.List++-- | Return the the subset of given ordinals within a given bound+-- and in order of the first occurrence seen.+--+-- Bound: @0 <= x < l@+--+-- >>> ordinalNub 3 [-1,2,1,4,2,3]+-- [2,1]+ordinalNub ::+  Int   {- ^ strict upper bound -} ->+  [Int] {- ^ ordinals           -} ->+  [Int] {- ^ unique, in-bound ordinals, in order seen -}+ordinalNub l xs = foldr (ordinalNubHelper l) (const []) xs IntSet.empty++ordinalNubHelper :: Int -> Int -> (IntSet -> [Int]) -> (IntSet -> [Int])+ordinalNubHelper l x next seen+  | outOfBounds || notUnique = next seen+  | otherwise                = x : next (IntSet.insert x seen)+  where+  outOfBounds = x < 0 || l <= x+  notUnique   = x `IntSet.member` seen++-- | \(\mathcal{O}(\min(m,n))\). The 'stripSuffix' function drops the given+-- suffix from a list. It returns 'Nothing' if the list did not end with the+-- suffix given, or 'Just' the list after the suffix, if it does.+--+-- >>> stripSuffix "bar" "foobar"+-- Just "foo"+--+-- >>> stripSuffix "foo" "foo"+-- Just ""+--+-- >>> stripSuffix "bar" "barfoo"+-- Nothing+--+-- >>> stripSuffix "foo" "barfoobaz"+-- Nothing+stripSuffix :: Eq a => [a] -> [a] -> Maybe [a]+stripSuffix qs xs0 = go xs0 zs+  where+    zs = drp qs xs0+    drp (_:ps) (_:xs) = drp ps xs+    drp [] xs = xs+    drp _  [] = []+    go (_:xs) (_:ys) = go xs ys+    go xs [] = zipWith const xs0 zs <$ guard (xs == qs)+    go [] _  = Nothing -- impossible+{-# INLINE stripSuffix #-}
+ src/Control/Lens/Internal/Magma.hs view
@@ -0,0 +1,273 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE RoleAnnotations #-}+-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Magma+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+----------------------------------------------------------------------------+module Control.Lens.Internal.Magma+  (+  -- * Magma+    Magma(..)+  , runMagma+  -- * Molten+  , Molten(..)+  -- * Mafic+  , Mafic(..)+  , runMafic+  -- * TakingWhile+  , TakingWhile(..)+  , runTakingWhile+  ) where++import Prelude ()++import Control.Comonad+import Control.Lens.Internal.Bazaar+import Control.Lens.Internal.Context+import Control.Lens.Internal.Indexed+import Control.Lens.Internal.Prelude+import Data.Functor.Apply+import Data.Functor.WithIndex+import Data.Foldable.WithIndex+import Data.Kind+import Data.Traversable.WithIndex++------------------------------------------------------------------------------+-- Magma+------------------------------------------------------------------------------++-- | This provides a way to peek at the internal structure of a+-- 'Control.Lens.Traversal.Traversal' or 'Control.Lens.Traversal.IndexedTraversal'+data Magma i t b a where+  MagmaAp   :: Magma i (x -> y) b a -> Magma i x b a -> Magma i y b a+  MagmaPure :: x -> Magma i x b a+  MagmaFmap :: (x -> y) -> Magma i x b a -> Magma i y b a+  Magma :: i -> a -> Magma i b b a++-- note the 3rd argument infers as phantom, but that would be unsound+type role Magma representational nominal nominal nominal++instance Functor (Magma i t b) where+  fmap f (MagmaAp x y)    = MagmaAp (fmap f x) (fmap f y)+  fmap _ (MagmaPure x)    = MagmaPure x+  fmap f (MagmaFmap xy x) = MagmaFmap xy (fmap f x)+  fmap f (Magma i a)  = Magma i (f a)++instance Foldable (Magma i t b) where+  foldMap f (MagmaAp x y)   = foldMap f x `mappend` foldMap f y+  foldMap _ MagmaPure{}     = mempty+  foldMap f (MagmaFmap _ x) = foldMap f x+  foldMap f (Magma _ a) = f a++instance Traversable (Magma i t b) where+  traverse f (MagmaAp x y)    = MagmaAp <$> traverse f x <*> traverse f y+  traverse _ (MagmaPure x)    = pure (MagmaPure x)+  traverse f (MagmaFmap xy x) = MagmaFmap xy <$> traverse f x+  traverse f (Magma i a)  = Magma i <$> f a++instance FunctorWithIndex i (Magma i t b) where+  imap f (MagmaAp x y)    = MagmaAp (imap f x) (imap f y)+  imap _ (MagmaPure x)    = MagmaPure x+  imap f (MagmaFmap xy x) = MagmaFmap xy (imap f x)+  imap f (Magma i a)      = Magma i (f i a)+  {-# INLINE imap #-}++instance FoldableWithIndex i (Magma i t b) where+  ifoldMap f (MagmaAp x y)   = ifoldMap f x `mappend` ifoldMap f y+  ifoldMap _ MagmaPure{}     = mempty+  ifoldMap f (MagmaFmap _ x) = ifoldMap f x+  ifoldMap f (Magma i a)     = f i a+  {-# INLINE ifoldMap #-}++instance TraversableWithIndex i (Magma i t b) where+  itraverse f (MagmaAp x y)    = MagmaAp <$> itraverse f x <*> itraverse f y+  itraverse _ (MagmaPure x)    = pure (MagmaPure x)+  itraverse f (MagmaFmap xy x) = MagmaFmap xy <$> itraverse f x+  itraverse f (Magma i a)      = Magma i <$> f i a+  {-# INLINE itraverse #-}++instance (Show i, Show a) => Show (Magma i t b a) where+  showsPrec d (MagmaAp x y) = showParen (d > 4) $+    showsPrec 4 x . showString " <*> " . showsPrec 5 y+  showsPrec d (MagmaPure _) = showParen (d > 10) $+    showString "pure .."+  showsPrec d (MagmaFmap _ x) = showParen (d > 4) $+    showString ".. <$> " . showsPrec 5 x+  showsPrec d (Magma i a) = showParen (d > 10) $+    showString "Magma " . showsPrec 11 i . showChar ' ' . showsPrec 11 a++-- | Run a 'Magma' where all the individual leaves have been converted to the+-- expected type+runMagma :: Magma i t a a -> t+runMagma (MagmaAp l r)   = runMagma l (runMagma r)+runMagma (MagmaFmap f r) = f (runMagma r)+runMagma (MagmaPure x)   = x+runMagma (Magma _ a) = a++------------------------------------------------------------------------------+-- Molten+------------------------------------------------------------------------------++-- | This is a a non-reassociating initially encoded version of 'Bazaar'.+newtype Molten i a b t = Molten { runMolten :: Magma i t b a }++instance Functor (Molten i a b) where+  fmap f (Molten xs) = Molten (MagmaFmap f xs)+  {-# INLINE fmap #-}++instance Apply (Molten i a b) where+  (<.>) = (<*>)+  {-# INLINE (<.>) #-}++instance Applicative (Molten i a b) where+  pure  = Molten #. MagmaPure+  {-# INLINE pure #-}+  Molten xs <*> Molten ys = Molten (MagmaAp xs ys)+  {-# INLINE (<*>) #-}++instance Sellable (Indexed i) (Molten i) where+  sell = Indexed (\i -> Molten #. Magma i)+  {-# INLINE sell #-}++instance Bizarre (Indexed i) (Molten i) where+  bazaar f (Molten (MagmaAp x y))   = bazaar f (Molten x) <*> bazaar f (Molten y)+  bazaar f (Molten (MagmaFmap g x)) = g <$> bazaar f (Molten x)+  bazaar _ (Molten (MagmaPure x))   = pure x+  bazaar f (Molten (Magma i a)) = indexed f i a++instance IndexedFunctor (Molten i) where+  ifmap f (Molten xs) = Molten (MagmaFmap f xs)+  {-# INLINE ifmap #-}++instance IndexedComonad (Molten i) where+  iextract (Molten (MagmaAp x y))   = iextract (Molten x) (iextract (Molten y))+  iextract (Molten (MagmaFmap f y)) = f (iextract (Molten y))+  iextract (Molten (MagmaPure x))   = x+  iextract (Molten (Magma _ a)) = a++  iduplicate (Molten (Magma i a)) = Molten #. Magma i <$> Molten (Magma i a)+  iduplicate (Molten (MagmaPure x))   = pure (pure x)+  iduplicate (Molten (MagmaFmap f y)) = iextend (fmap f) (Molten y)+  iduplicate (Molten (MagmaAp x y))   = iextend (<*>) (Molten x) <*> iduplicate (Molten y)++  iextend k (Molten (Magma i a)) = (k .# Molten) . Magma i <$> Molten (Magma i a)+  iextend k (Molten (MagmaPure x))   = pure (k (pure x))+  iextend k (Molten (MagmaFmap f y)) = iextend (k . fmap f) (Molten y)+  iextend k (Molten (MagmaAp x y))   = iextend (\x' y' -> k $ x' <*> y') (Molten x) <*> iduplicate (Molten y)++instance a ~ b => Comonad (Molten i a b) where+  extract   = iextract+  {-# INLINE extract #-}+  extend    = iextend+  {-# INLINE extend #-}+  duplicate = iduplicate+  {-# INLINE duplicate #-}++------------------------------------------------------------------------------+-- Mafic+------------------------------------------------------------------------------++-- | This is used to generate an indexed magma from an unindexed source+--+-- By constructing it this way we avoid infinite reassociations in sums where possible.+data Mafic a b t = Mafic Int (Int -> Magma Int t b a)++-- | Generate a 'Magma' using from a prefix sum.+runMafic :: Mafic a b t -> Magma Int t b a+runMafic (Mafic _ k) = k 0++instance Functor (Mafic a b) where+  fmap f (Mafic w k) = Mafic w (MagmaFmap f . k)+  {-# INLINE fmap #-}++instance Apply (Mafic a b) where+  Mafic wf mf <.> ~(Mafic wa ma) = Mafic (wf + wa) $ \o -> MagmaAp (mf o) (ma (o + wf))+  {-# INLINE (<.>) #-}++instance Applicative (Mafic a b) where+  pure a = Mafic 0 $ \_ -> MagmaPure a+  {-# INLINE pure #-}+  Mafic wf mf <*> ~(Mafic wa ma) = Mafic (wf + wa) $ \o -> MagmaAp (mf o) (ma (o + wf))+  {-# INLINE (<*>) #-}++instance Sellable (->) Mafic where+  sell a = Mafic 1 $ \ i -> Magma i a+  {-# INLINE sell #-}++instance Bizarre (Indexed Int) Mafic where+  bazaar (pafb :: Indexed Int a (f b)) (Mafic _ k) = go (k 0) where+    go :: Magma Int t b a -> f t+    go (MagmaAp x y)   = go x <*> go y+    go (MagmaFmap f x) = f <$> go x+    go (MagmaPure x)   = pure x+    go (Magma i a) = indexed pafb (i :: Int) a+  {-# INLINE bazaar #-}++instance IndexedFunctor Mafic where+  ifmap f (Mafic w k) = Mafic w (MagmaFmap f . k)+  {-# INLINE ifmap #-}++------------------------------------------------------------------------------+-- TakingWhile+------------------------------------------------------------------------------++-- | This is used to generate an indexed magma from an unindexed source+--+-- By constructing it this way we avoid infinite reassociations where possible.+--+-- In @'TakingWhile' p g a b t@, @g@ has a @nominal@ role to avoid exposing an illegal _|_ via 'Contravariant',+-- while the remaining arguments are degraded to a @nominal@ role by the invariants of 'Magma'+data TakingWhile p (g :: Type -> Type) a b t = TakingWhile Bool t (Bool -> Magma () t b (Corep p a))+type role TakingWhile nominal nominal nominal nominal nominal++-- | Generate a 'Magma' with leaves only while the predicate holds from left to right.+runTakingWhile :: TakingWhile p f a b t -> Magma () t b (Corep p a)+runTakingWhile (TakingWhile _ _ k) = k True++instance Functor (TakingWhile p f a b) where+  fmap f (TakingWhile w t k) = let ft = f t in TakingWhile w ft $ \b -> if b then MagmaFmap f (k b) else MagmaPure ft+  {-# INLINE fmap #-}++instance Apply (TakingWhile p f a b) where+  TakingWhile wf tf mf <.> ~(TakingWhile wa ta ma) = TakingWhile (wf && wa) (tf ta) $ \o ->+    if o then MagmaAp (mf True) (ma wf) else MagmaPure (tf ta)+  {-# INLINE (<.>) #-}++instance Applicative (TakingWhile p f a b) where+  pure a = TakingWhile True a $ \_ -> MagmaPure a+  {-# INLINE pure #-}+  TakingWhile wf tf mf <*> ~(TakingWhile wa ta ma) = TakingWhile (wf && wa) (tf ta) $ \o ->+    if o then MagmaAp (mf True) (ma wf) else MagmaPure (tf ta)+  {-# INLINE (<*>) #-}++instance Corepresentable p => Bizarre p (TakingWhile p g) where+  bazaar (pafb :: p a (f b)) ~(TakingWhile _ _ k) = go (k True) where+    go :: Magma () t b (Corep p a) -> f t+    go (MagmaAp x y)  = go x <*> go y+    go (MagmaFmap f x)  = f <$> go x+    go (MagmaPure x)    = pure x+    go (Magma _ wa) = cosieve pafb wa+  {-# INLINE bazaar #-}++-- This constraint is unused intentionally, it protects TakingWhile+instance Contravariant f => Contravariant (TakingWhile p f a b) where+  contramap _ = (<$) (error "contramap: TakingWhile")+  {-# INLINE contramap #-}++instance IndexedFunctor (TakingWhile p f) where+  ifmap = fmap+  {-# INLINE ifmap #-}
+ src/Control/Lens/Internal/Prelude.hs view
@@ -0,0 +1,120 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Trustworthy #-}+#include "lens-common.h"+-- | Module which does most common imports (and related CPP)+-- needed across the lens library.+--+-- This module is intended to stay in other-modules of lens,+-- perfectly we'd just use @base-compat-batteries@+-- and not reinvent the wheel.+-- That's a reason why this module is different from+-- other .Internal modules, which are exposed-modules.+--+-- Also this is a "fat" Prelude, re-exporting commonly used,+-- non conflicting symbols.+--+module Control.Lens.Internal.Prelude+  ( module Prelude+  , Semigroup (..)+  , Monoid (..)+  , Foldable, foldMap, foldr, foldl, foldl', elem, null, length, traverse_+  , Traversable (..)+  , Applicative (..)+  , (&), (<&>), (<$>), (<$)+  -- * Data types+  , ZipList (..)+  , NonEmpty (..)+  -- * Functors+  , Identity (..)+  , Compose (..)+  , Const (..)+  -- * Control.Applicative+  , Alternative (..), WrappedMonad (..)+#if !MIN_VERSION_base(4,10,0)+  , liftA2+#endif+  -- * Data.Coerce+  , Coercible, coerce+  -- * Data.Contravariant+  , Contravariant (..), phantom+  -- * Data.Monoid+  , Endo (..), Dual (..)+  -- * Data.Profunctor+  , Profunctor (..)+  , Choice (..), Cochoice (..)+  , Strong (..), Costrong (..)+  , Corepresentable (..)+  , Sieve (..), Cosieve (..)+  -- * Data.Proxy+  , Proxy (..)+  -- * Data.Tagged+  , Tagged (..)+  -- * Data.Void+  , Void, absurd+  -- * Data.Word+  , Word+  ) where++import Prelude hiding+    ( userError -- hiding something always helps with CPP+    , Applicative (..)+    , Foldable (..)+    , Traversable (..)+    , Monoid (..)+    , (<$>), (<$)+#if MIN_VERSION_base(4,13,0)+    , Semigroup (..)+#endif+    , Word+    )++-- Prelude+import Control.Applicative (Applicative (..), (<$>), (<$)) -- N.B. liftA2+import Data.Foldable (Foldable, foldMap, elem, foldr, foldl, foldl', traverse_) -- N.B. we don't define Foldable instances, so this way is makes less CPP+import Data.Monoid (Monoid (..))+import Data.Semigroup (Semigroup (..))+import Data.Traversable (Traversable (..))+import Data.Word (Word)++-- Extras+import Data.Function ((&))+import Data.Foldable (length, null)++#if !MIN_VERSION_base(4,10,0)+import Control.Applicative (liftA2)+#endif++#if MIN_VERSION_base(4,11,0)+import Data.Functor ((<&>))+#endif++import Control.Applicative (Alternative (..), Const (..), WrappedMonad (..), ZipList (..))+import Data.Coerce (Coercible, coerce)+import Data.Functor.Compose (Compose (..))+import Data.Functor.Contravariant (Contravariant (..), phantom)+import Data.Functor.Identity (Identity (..))+import Data.List.NonEmpty (NonEmpty (..))+import Data.Monoid (Endo (..), Dual (..))+import Data.Profunctor (Strong (..), Choice (..), Cochoice (..), Costrong (..))+import Data.Profunctor.Rep (Corepresentable (..)) -- N.B. no Representable+import Data.Profunctor.Sieve (Sieve (..), Cosieve (..))+import Data.Profunctor.Unsafe (Profunctor (..))+import Data.Proxy (Proxy (..))+import Data.Tagged (Tagged (..))+import Data.Void (Void, absurd)++-- TraversableWithIndex instances for tagged, vector and unordered-containers+-- We import this here, so the instances propagate through all (most) of @lens@.+import Data.Functor.WithIndex.Instances ()++#if !(MIN_VERSION_base(4,11,0))+-- | Infix flipped 'fmap'.+--+-- @+-- ('<&>') = 'flip' 'fmap'+-- @+(<&>) :: Functor f => f a -> (a -> b) -> f b+as <&> f = f <$> as+{-# INLINE (<&>) #-}+infixl 1 <&>+#endif
+ src/Control/Lens/Internal/Prism.hs view
@@ -0,0 +1,61 @@+{-# LANGUAGE ScopedTypeVariables #-}+-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Prism+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+----------------------------------------------------------------------------+module Control.Lens.Internal.Prism+  ( Market(..)+  , Market'+  ) where++import Prelude ()++import Control.Lens.Internal.Prelude++------------------------------------------------------------------------------+-- Prism: Market+------------------------------------------------------------------------------++-- | This type is used internally by the 'Control.Lens.Prism.Prism' code to+-- provide efficient access to the two parts of a 'Prism'.+data Market a b s t = Market (b -> t) (s -> Either t a)++-- | @type 'Market'' a s t = 'Market' a a s t@+type Market' a = Market a a++instance Functor (Market a b s) where+  fmap f (Market bt seta) = Market (f . bt) (either (Left . f) Right . seta)+  {-# INLINE fmap #-}++instance Profunctor (Market a b) where+  dimap f g (Market bt seta) = Market (g . bt) (either (Left . g) Right . seta . f)+  {-# INLINE dimap #-}+  lmap f (Market bt seta) = Market bt (seta . f)+  {-# INLINE lmap #-}+  rmap f (Market bt seta) = Market (f . bt) (either (Left . f) Right . seta)+  {-# INLINE rmap #-}++  (#.) _ = coerce+  {-# INLINE (#.) #-}+  (.#) p _ = coerce p+  {-# INLINE (.#) #-}++instance Choice (Market a b) where+  left' (Market bt seta) = Market (Left . bt) $ \sc -> case sc of+    Left s -> case seta s of+      Left t -> Left (Left t)+      Right a -> Right a+    Right c -> Left (Right c)+  {-# INLINE left' #-}+  right' (Market bt seta) = Market (Right . bt) $ \cs -> case cs of+    Left c -> Left (Left c)+    Right s -> case seta s of+      Left t -> Left (Right t)+      Right a -> Right a+  {-# INLINE right' #-}
+ src/Control/Lens/Internal/PrismTH.hs view
@@ -0,0 +1,539 @@+{-# LANGUAGE CPP #-}+#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-}+#endif++#include "lens-common.h"++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.PrismTH+-- Copyright   :  (C) 2014-2016 Edward Kmett and Eric Mertens+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-----------------------------------------------------------------------------++module Control.Lens.Internal.PrismTH+  ( makePrisms+  , makeClassyPrisms+  , makeDecPrisms+  ) where++import Control.Applicative+import Control.Lens.Getter+import Control.Lens.Internal.TH+import Control.Lens.Lens+import Control.Lens.Setter+import Control.Monad+import Data.Char (isUpper)+import qualified Data.List as List+import Data.Set.Lens+import Data.Traversable+import Language.Haskell.TH+import qualified Language.Haskell.TH.Datatype as D+import qualified Language.Haskell.TH.Datatype.TyVarBndr as D+import Language.Haskell.TH.Lens+import qualified Data.Map as Map+import qualified Data.Set as Set+import Data.Set (Set)+import Prelude++-- | Generate a 'Prism' for each constructor of a data type.+-- Isos generated when possible.+-- Reviews are created for constructors with existentially+-- quantified constructors and GADTs.+--+-- /e.g./+--+-- @+-- data FooBarBaz a+--   = Foo Int+--   | Bar a+--   | Baz Int Char+-- makePrisms ''FooBarBaz+-- @+--+-- will create+--+-- @+-- _Foo :: Prism' (FooBarBaz a) Int+-- _Bar :: Prism (FooBarBaz a) (FooBarBaz b) a b+-- _Baz :: Prism' (FooBarBaz a) (Int, Char)+-- @+makePrisms :: Name {- ^ Type constructor name -} -> DecsQ+makePrisms = makePrisms' True+++-- | Generate a 'Prism' for each constructor of a data type+-- and combine them into a single class. No Isos are created.+-- Reviews are created for constructors with existentially+-- quantified constructors and GADTs.+--+-- /e.g./+--+-- @+-- data FooBarBaz a+--   = Foo Int+--   | Bar a+--   | Baz Int Char+-- makeClassyPrisms ''FooBarBaz+-- @+--+-- will create+--+-- @+-- class AsFooBarBaz s a | s -> a where+--   _FooBarBaz :: Prism' s (FooBarBaz a)+--   _Foo :: Prism' s Int+--   _Bar :: Prism' s a+--   _Baz :: Prism' s (Int,Char)+--+--   _Foo = _FooBarBaz . _Foo+--   _Bar = _FooBarBaz . _Bar+--   _Baz = _FooBarBaz . _Baz+--+-- instance AsFooBarBaz (FooBarBaz a) a+-- @+--+-- Generate an "As" class of prisms. Names are selected by prefixing the constructor+-- name with an underscore.  Constructors with multiple fields will+-- construct Prisms to tuples of those fields.+--+-- In the event that the name of a data type is also the name of one of its+-- constructors, the name of the 'Prism' generated for the data type will be+-- prefixed with an extra @_@ (if the data type name is prefix) or @.@ (if the+-- name is infix) to disambiguate it from the 'Prism' for the corresponding+-- constructor. For example, this code:+--+-- @+-- data Quux = Quux Int | Fred Bool+-- makeClassyPrisms ''Quux+-- @+--+-- will create:+--+-- @+-- class AsQuux s where+--   __Quux :: Prism' s Quux -- Data type prism+--   _Quux :: Prism' s Int   -- Constructor prism+--   _Fred :: Prism' s Bool+--+--   _Quux = __Quux . _Quux+--   _Fred = __Quux . _Fred+--+-- instance AsQuux Quux+-- @+makeClassyPrisms :: Name {- ^ Type constructor name -} -> DecsQ+makeClassyPrisms = makePrisms' False+++-- | Main entry point into Prism generation for a given type constructor name.+makePrisms' :: Bool -> Name -> DecsQ+makePrisms' normal typeName =+  do info <- D.reifyDatatype typeName+     let cls | normal    = Nothing+             | otherwise = Just (D.datatypeName info)+         cons = D.datatypeCons info+     makeConsPrisms (datatypeTypeKinded info) (map normalizeCon cons) cls+++-- | Generate prisms for the given 'Dec'+makeDecPrisms :: Bool {- ^ generate top-level definitions -} -> Dec -> DecsQ+makeDecPrisms normal dec =+  do info <- D.normalizeDec dec+     let cls | normal    = Nothing+             | otherwise = Just (D.datatypeName info)+         cons = D.datatypeCons info+     makeConsPrisms (datatypeTypeKinded info) (map normalizeCon cons) cls+++-- | Generate prisms for the given type, normalized constructors, and+-- an optional name to be used for generating a prism class.+-- This function dispatches between Iso generation, normal top-level+-- prisms, and classy prisms.+makeConsPrisms :: Type -> [NCon] -> Maybe Name -> DecsQ++-- special case: single constructor, not classy -> make iso+makeConsPrisms t [con@(NCon _ [] [] _)] Nothing = makeConIso t con++-- top-level definitions+makeConsPrisms t cons Nothing =+  fmap concat $ for cons $ \con ->+    do let conName = view nconName con+       stab <- computeOpticType t cons con+       let n = prismName conName+       sequenceA+         ( [ sigD n (return (quantifyType [] (stabToType Set.empty stab)))+           , valD (varP n) (normalB (makeConOpticExp stab cons con)) []+           ]+           ++ inlinePragma n+         )+++-- classy prism class and instance+makeConsPrisms t cons (Just typeName) =+  sequenceA+    [ makeClassyPrismClass t className methodName cons+    , makeClassyPrismInstance t className methodName cons+    ]+  where+  typeNameBase = nameBase typeName+  className = mkName ("As" ++ typeNameBase)+  sameNameAsCon = any (\con -> nameBase (view nconName con) == typeNameBase) cons+  methodName = prismName' sameNameAsCon typeName+++data OpticType = PrismType | ReviewType+data Stab  = Stab Cxt OpticType Type Type Type Type++simplifyStab :: Stab -> Stab+simplifyStab (Stab cx ty _ t _ b) = Stab cx ty t t b b+  -- simplification uses t and b because those types+  -- are interesting in the Review case++stabSimple :: Stab -> Bool+stabSimple (Stab _ _ s t a b) = s == t && a == b++stabToType :: Set Name -> Stab -> Type+stabToType clsTVBNames stab@(Stab cx ty s t a b) =+  quantifyType' clsTVBNames cx stabTy+  where+  stabTy =+    case ty of+      PrismType  | stabSimple stab -> prism'TypeName  `conAppsT` [t,b]+                 | otherwise       -> prismTypeName   `conAppsT` [s,t,a,b]+      ReviewType                   -> reviewTypeName  `conAppsT` [t,b]++stabType :: Stab -> OpticType+stabType (Stab _ o _ _ _ _) = o++computeOpticType :: Type -> [NCon] -> NCon -> Q Stab+computeOpticType t cons con =+  do let cons' = List.delete con cons+     if null (_nconVars con)+         then computePrismType t (view nconCxt con) cons' con+         else computeReviewType t (view nconCxt con) (view nconTypes con)+++computeReviewType :: Type -> Cxt -> [Type] -> Q Stab+computeReviewType s' cx tys =+  do let t = s'+     s <- fmap VarT (newName "s")+     a <- fmap VarT (newName "a")+     b <- toTupleT (map return tys)+     return (Stab cx ReviewType s t a b)+++-- | Compute the full type-changing Prism type given an outer type,+-- list of constructors, and target constructor name. Additionally+-- return 'True' if the resulting type is a "simple" prism.+computePrismType :: Type -> Cxt -> [NCon] -> NCon -> Q Stab+computePrismType t cx cons con =+  do let ts      = view nconTypes con+         unbound = setOf typeVars t Set.\\ setOf typeVars cons+     sub <- sequenceA (Map.fromSet (newName . nameBase) unbound)+     b   <- toTupleT (map return ts)+     a   <- toTupleT (map return (substTypeVars sub ts))+     let s = substTypeVars sub t+     return (Stab cx PrismType s t a b)+++computeIsoType :: Type -> [Type] -> TypeQ+computeIsoType t' fields =+  do sub <- sequenceA (Map.fromSet (newName . nameBase) (setOf typeVars t'))+     let t = return                    t'+         s = return (substTypeVars sub t')+         b = toTupleT (map return                    fields)+         a = toTupleT (map return (substTypeVars sub fields))++         ty | Map.null sub = appsT (conT iso'TypeName) [t,b]+            | otherwise    = appsT (conT isoTypeName) [s,t,a,b]++     quantifyType [] <$> ty++++-- | Construct either a Review or Prism as appropriate+makeConOpticExp :: Stab -> [NCon] -> NCon -> ExpQ+makeConOpticExp stab cons con =+  case stabType stab of+    PrismType  -> makeConPrismExp stab cons con+    ReviewType -> makeConReviewExp con+++-- | Construct an iso declaration+makeConIso :: Type -> NCon -> DecsQ+makeConIso s con =+  do let ty      = computeIsoType s (view nconTypes con)+         defName = prismName (view nconName con)+     sequenceA+       ( [ sigD       defName  ty+         , valD (varP defName) (normalB (makeConIsoExp con)) []+         ] +++         inlinePragma defName+       )+++-- | Construct prism expression+--+-- prism <<reviewer>> <<remitter>>+makeConPrismExp ::+  Stab ->+  [NCon] {- ^ constructors       -} ->+  NCon   {- ^ target constructor -} ->+  ExpQ+makeConPrismExp stab cons con = appsE [varE prismValName, reviewer, remitter]+  where+  ts = view nconTypes con+  fields  = length ts+  conName = view nconName con++  reviewer                   = makeReviewer       conName fields+  remitter | stabSimple stab = makeSimpleRemitter conName (length cons) fields+           | otherwise       = makeFullRemitter cons conName+++-- | Construct an Iso expression+--+-- iso <<reviewer>> <<remitter>>+makeConIsoExp :: NCon -> ExpQ+makeConIsoExp con = appsE [varE isoValName, remitter, reviewer]+  where+  conName = view nconName con+  fields  = length (view nconTypes con)++  reviewer = makeReviewer    conName fields+  remitter = makeIsoRemitter conName fields+++-- | Construct a Review expression+--+-- unto (\(x,y,z) -> Con x y z)+makeConReviewExp :: NCon -> ExpQ+makeConReviewExp con = appE (varE untoValName) reviewer+  where+  conName = view nconName con+  fields  = length (view nconTypes con)++  reviewer = makeReviewer conName fields+++------------------------------------------------------------------------+-- Prism and Iso component builders+------------------------------------------------------------------------+++-- | Construct the review portion of a prism.+--+-- (\(x,y,z) -> Con x y z) :: b -> t+makeReviewer :: Name -> Int -> ExpQ+makeReviewer conName fields =+  do xs <- newNames "x" fields+     lam1E (toTupleP (map varP xs))+           (conE conName `appsE1` map varE xs)+++-- | Construct the remit portion of a prism.+-- Pattern match only target constructor, no type changing+--+-- (\x -> case s of+--          Con x y z -> Right (x,y,z)+--          _         -> Left x+-- ) :: s -> Either s a+makeSimpleRemitter ::+  Name {- The name of the constructor on which this prism focuses -} ->+  Int  {- The number of constructors the parent data type has     -} ->+  Int  {- The number of fields the constructor has                -} ->+  ExpQ+makeSimpleRemitter conName numCons fields =+  do x  <- newName "x"+     xs <- newNames "y" fields+     let matches =+           [ match (conP conName (map varP xs))+                   (normalB (appE (conE rightDataName) (toTupleE (map varE xs))))+                   []+           ] +++           [ match wildP (normalB (appE (conE leftDataName) (varE x))) []+           | numCons > 1 -- Only generate a catch-all case if there is at least+                         -- one constructor besides the one being focused on.+           ]+     lam1E (varP x) (caseE (varE x) matches)+++-- | Pattern match all constructors to enable type-changing+--+-- (\x -> case s of+--          Con x y z -> Right (x,y,z)+--          Other_n w   -> Left (Other_n w)+-- ) :: s -> Either t a+makeFullRemitter :: [NCon] -> Name -> ExpQ+makeFullRemitter cons target =+  do x <- newName "x"+     lam1E (varP x) (caseE (varE x) (map mkMatch cons))+  where+  mkMatch (NCon conName _ _ n) =+    do xs <- newNames "y" (length n)+       match (conP conName (map varP xs))+             (normalB+               (if conName == target+                  then appE (conE rightDataName) (toTupleE (map varE xs))+                  else appE (conE leftDataName) (conE conName `appsE1` map varE xs)))+             []+++-- | Construct the remitter suitable for use in an 'Iso'+--+-- (\(Con x y z) -> (x,y,z)) :: s -> a+makeIsoRemitter :: Name -> Int -> ExpQ+makeIsoRemitter conName fields =+  do xs <- newNames "x" fields+     lam1E (conP conName (map varP xs))+           (toTupleE (map varE xs))+++------------------------------------------------------------------------+-- Classy prisms+------------------------------------------------------------------------+++-- | Construct the classy prisms class for a given type and constructors.+--+-- class ClassName r <<vars in type>> | r -> <<vars in Type>> where+--   topMethodName   :: Prism' r Type+--   conMethodName_n :: Prism' r conTypes_n+--   conMethodName_n = topMethodName . conMethodName_n+makeClassyPrismClass ::+  Type   {- Outer type      -} ->+  Name   {- Class name      -} ->+  Name   {- Top method name -} ->+  [NCon] {- Constructors    -} ->+  DecQ+makeClassyPrismClass t className methodName cons =+  do r <- newName "r"+     let methodType = appsT (conT prism'TypeName) [varT r,return t]+     methodss <- traverse (mkMethod r) cons'+     classD (cxt[]) className (D.plainTV r : vs) (fds r)+       ( sigD methodName methodType+       : map return (concat methodss)+       )++  where+  mkMethod r con =+    do Stab cx o _ _ _ b <- computeOpticType t cons con+       let rTy   = VarT r+           stab' = Stab cx o rTy rTy b b+           defName = view nconName con+           body    = appsE [varE composeValName, varE methodName, varE defName]+       sequenceA+         [ sigD defName        (return (stabToType (Set.fromList (r:vNames)) stab'))+         , valD (varP defName) (normalB body) []+         ]++  cons'         = map (over nconName prismName) cons+  vs            = D.changeTVFlags bndrReq $ D.freeVariablesWellScoped [t]+  vNames        = map D.tvName vs+  fds r+    | null vs   = []+    | otherwise = [FunDep [r] vNames]++++-- | Construct the classy prisms instance for a given type and constructors.+--+-- instance Classname OuterType where+--   topMethodName = id+--   conMethodName_n = <<prism>>+makeClassyPrismInstance ::+  Type ->+  Name     {- Class name      -} ->+  Name     {- Top method name -} ->+  [NCon] {- Constructors    -} ->+  DecQ+makeClassyPrismInstance s className methodName cons =+  do let vs = D.freeVariablesWellScoped [s]+         cls = className `conAppsT` (s : map tvbToType vs)++     instanceD (cxt[]) (return cls)+       (   valD (varP methodName)+                (normalB (varE idValName)) []+       : [ do stab <- computeOpticType s cons con+              let stab' = simplifyStab stab+              valD (varP (prismName conName))+                (normalB (makeConOpticExp stab' cons con)) []+           | con <- cons+           , let conName = view nconName con+           ]+       )+++------------------------------------------------------------------------+-- Utilities+------------------------------------------------------------------------+++-- | Normalized constructor+data NCon = NCon+  { _nconName :: Name+  , _nconVars :: [Name]+  , _nconCxt  :: Cxt+  , _nconTypes :: [Type]+  }+  deriving (Eq)++instance HasTypeVars NCon where+  typeVarsEx s f (NCon x vars y z) = NCon x vars <$> typeVarsEx s' f y <*> typeVarsEx s' f z+    where s' = List.foldl' (flip Set.insert) s vars++nconName :: Lens' NCon Name+nconName f x = fmap (\y -> x {_nconName = y}) (f (_nconName x))++nconCxt :: Lens' NCon Cxt+nconCxt f x = fmap (\y -> x {_nconCxt = y}) (f (_nconCxt x))++nconTypes :: Lens' NCon [Type]+nconTypes f x = fmap (\y -> x {_nconTypes = y}) (f (_nconTypes x))+++-- | Normalize a single 'Con' to its constructor name and field types.+normalizeCon :: D.ConstructorInfo -> NCon+normalizeCon info = NCon (D.constructorName info)+                         (D.tvName <$> D.constructorVars info)+                         (D.constructorContext info)+                         (D.constructorFields info)+++-- | Compute a prism's name by prefixing an underscore for normal+-- constructors and period for operators.+prismName :: Name -> Name+prismName = prismName' False++-- | Compute a prism's name with a special case for when the type+-- constructor matches one of the value constructors.+--+-- The overlapping flag will be 'True' in the event that:+--+-- 1. We are generating the name of a classy prism for a+--    data type, and+-- 2. The data type shares a name with one of its+--    constructors (e.g., @data A = A@).+--+-- In such a scenario, we take care not to generate the same+-- prism name that the constructor receives (e.g., @_A@).+-- For prefix names, we accomplish this by adding an extra+-- underscore; for infix names, an extra dot.+prismName' ::+  Bool {- ^ overlapping constructor -} ->+  Name {- ^ type constructor        -} ->+  Name {- ^ prism name              -}+prismName' sameNameAsCon n =+  case nameBase n of+    [] -> error "prismName: empty name base?"+    nb@(x:_) | isUpper x -> mkName (prefix '_' nb)+             | otherwise -> mkName (prefix '.' nb) -- operator+  where+    prefix :: Char -> String -> String+    prefix char str | sameNameAsCon = char:char:str+                    | otherwise     =      char:str
+ src/Control/Lens/Internal/Profunctor.hs view
@@ -0,0 +1,17 @@+module Control.Lens.Internal.Profunctor +  ( WrappedPafb (..)+  ) where++import Prelude ()+import Control.Lens.Internal.Prelude++newtype WrappedPafb f p a b = WrapPafb { unwrapPafb :: p a (f b) }++instance (Functor f, Profunctor p) => Profunctor (WrappedPafb f p) where+  dimap f g (WrapPafb p) = WrapPafb $ dimap f (fmap g) p++instance (Applicative f, Choice p) => Choice (WrappedPafb f p) where+  left' (WrapPafb p) = WrapPafb $ rmap sequenceL $ left' p+    where+      sequenceL (Left a) = fmap Left a+      sequenceL (Right a) = pure $ Right a
+ src/Control/Lens/Internal/Review.hs view
@@ -0,0 +1,42 @@+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Review+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  non-portable+--+----------------------------------------------------------------------------+module Control.Lens.Internal.Review+  (+  -- * Internal Classes+    Reviewable+  -- * Reviews+  , retagged+  ) where++import Data.Bifunctor+import Data.Profunctor+import Data.Void++-- | This class is provided mostly for backwards compatibility with lens 3.8,+-- but it can also shorten type signatures.+class (Profunctor p, Bifunctor p) => Reviewable p+instance (Profunctor p, Bifunctor p) => Reviewable p++------------------------------------------------------------------------------+-- Review: Reviewed+------------------------------------------------------------------------------++-- | This is a profunctor used internally to implement "Review"+--+-- It plays a role similar to that of 'Control.Lens.Internal.Getter.Accessor'+-- or 'Const' do for "Control.Lens.Getter"+retagged :: (Profunctor p, Bifunctor p) => p a b -> p s b+retagged = first absurd . lmap absurd
+ src/Control/Lens/Internal/Setter.hs view
@@ -0,0 +1,60 @@+{-# LANGUAGE CPP #-}++{-# LANGUAGE Trustworthy #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Setter+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  non-portable+--+----------------------------------------------------------------------------+module Control.Lens.Internal.Setter+  (+  -- ** Setters+    Settable(..)+  ) where++import Prelude ()++import Control.Applicative.Backwards+import Control.Lens.Internal.Prelude+import Data.Distributive++-----------------------------------------------------------------------------+-- Settable+-----------------------------------------------------------------------------++-- | Anything 'Settable' must be isomorphic to the 'Identity' 'Functor'.+class (Applicative f, Distributive f, Traversable f) => Settable f where+  untainted :: f a -> a++  untaintedDot :: Profunctor p => p a (f b) -> p a b+  untaintedDot g = g `seq` rmap untainted g+  {-# INLINE untaintedDot #-}++  taintedDot :: Profunctor p => p a b -> p a (f b)+  taintedDot g = g `seq` rmap pure g+  {-# INLINE taintedDot #-}++-- | So you can pass our 'Control.Lens.Setter.Setter' into combinators from other lens libraries.+instance Settable Identity where+  untainted = runIdentity+  {-# INLINE untainted #-}+  untaintedDot = (runIdentity #.)+  {-# INLINE untaintedDot #-}+  taintedDot = (Identity #.)+  {-# INLINE taintedDot #-}++-- | 'Control.Lens.Fold.backwards'+instance Settable f => Settable (Backwards f) where+  untainted = untaintedDot forwards+  {-# INLINE untainted #-}++instance (Settable f, Settable g) => Settable (Compose f g) where+  untainted = untaintedDot (untaintedDot getCompose)+  {-# INLINE untainted #-}+
+ src/Control/Lens/Internal/TH.hs view
@@ -0,0 +1,268 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE TemplateHaskellQuotes #-}+#ifdef TRUSTWORTHY+# if MIN_VERSION_template_haskell(2,12,0)+{-# LANGUAGE Safe #-}+# else+{-# LANGUAGE Trustworthy #-}+# endif+#endif++#include "lens-common.h"++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.TH+-- Copyright   :  (C) 2013-2016 Edward Kmett and Eric Mertens+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+----------------------------------------------------------------------------+module Control.Lens.Internal.TH+  ( module Control.Lens.Internal.TH+#if MIN_VERSION_template_haskell(2,21,0) || MIN_VERSION_th_abstraction(0,6,0)+  , D.TyVarBndrVis+  , D.bndrReq+#endif+  ) where++import Control.Lens.Iso+import Control.Lens.Prism+import Control.Lens.Review+import Control.Lens.Type+import Control.Lens.Wrapped+import Data.Functor.Contravariant+import qualified Data.Set as Set+import Data.Set (Set)+import Language.Haskell.TH+import qualified Language.Haskell.TH.Datatype as D+import qualified Language.Haskell.TH.Datatype.TyVarBndr as D++-- | Apply arguments to a type constructor+appsT :: TypeQ -> [TypeQ] -> TypeQ+appsT = foldl appT++-- | Apply arguments to a function+appsE1 :: ExpQ -> [ExpQ] -> ExpQ+appsE1 = foldl appE++-- | Construct a tuple type given a list of types.+toTupleT :: [TypeQ] -> TypeQ+toTupleT [x] = x+toTupleT xs = appsT (tupleT (length xs)) xs++-- | Construct a tuple value given a list of expressions.+toTupleE :: [ExpQ] -> ExpQ+toTupleE [x] = x+toTupleE xs = tupE xs++-- | Construct a tuple pattern given a list of patterns.+toTupleP :: [PatQ] -> PatQ+toTupleP [x] = x+toTupleP xs = tupP xs++-- | Apply arguments to a type constructor.+conAppsT :: Name -> [Type] -> Type+conAppsT conName = foldl AppT (ConT conName)++-- | Generate many new names from a given base name.+newNames :: String {- ^ base name -} -> Int {- ^ count -} -> Q [Name]+newNames base n = sequence [ newName (base++show i) | i <- [1..n] ]++-- | Decompose an applied type into its individual components. For example, this:+--+-- @+-- Either Int Char+-- @+--+-- would be unfolded to this:+--+-- @+-- ('ConT' ''Either, ['ConT' ''Int, 'ConT' ''Char])+-- @+--+-- This function ignores explicit parentheses and visible kind applications.+unfoldType :: Type -> (Type, [Type])+unfoldType = go []+  where+    go :: [Type] -> Type -> (Type, [Type])+    go acc (ForallT _ _ ty) = go acc ty+    go acc (AppT ty1 ty2)   = go (ty2:acc) ty1+    go acc (SigT ty _)      = go acc ty+    go acc (ParensT ty)     = go acc ty+#if MIN_VERSION_template_haskell(2,15,0)+    go acc (AppKindT ty _)  = go acc ty+#endif+    go acc ty               = (ty, acc)++-- Construct a 'Type' using the datatype's type constructor and type+-- parameters. Unlike 'D.datatypeType', kind signatures are preserved to+-- some extent. (See the comments for 'dropSigsIfNonDataFam' below for more+-- details on this.)+datatypeTypeKinded :: D.DatatypeInfo -> Type+datatypeTypeKinded di+  = foldl AppT (ConT (D.datatypeName di))+  $ dropSigsIfNonDataFam di+  $ D.datatypeInstTypes di++-- | In an effort to prevent users from having to enable KindSignatures every+-- time that they use lens' TH functionality, we strip off reified kind+-- annotations from when:+--+-- 1. The kind of a type does not contain any kind variables. If it *does*+--    contain kind variables, we want to preserve them so that we can generate+--    type signatures that preserve the dependency order of kind and type+--    variables. (The data types in test/T917.hs contain examples where this+--    is important.) This will require enabling `PolyKinds`, but since+--    `PolyKinds` implies `KindSignatures`, we can at least accomplish two+--    things at once.+-- 2. The data type is not an instance of a data family. We make an exception+--    for data family instances, since the presence or absence of a kind+--    annotation can be the difference between typechecking or not.+--    (See T917DataFam in tests/T917.hs for an example.) Moreover, the+--    `TypeFamilies` extension implies `KindSignatures`.+dropSigsIfNonDataFam :: D.DatatypeInfo -> [Type] -> [Type]+dropSigsIfNonDataFam di+  | isDataFamily (D.datatypeVariant di) = id+  | otherwise                           = map dropSig+  where+    dropSig :: Type -> Type+    dropSig (SigT t k) | null (D.freeVariables k) = t+    dropSig t                                     = t++-- | Template Haskell wants type variables declared in a forall, so+-- we find all free type variables in a given type and declare them.+quantifyType :: Cxt -> Type -> Type+quantifyType = quantifyType' Set.empty++-- | This function works like 'quantifyType' except that it takes+-- a list of variables to exclude from quantification.+quantifyType' :: Set Name -> Cxt -> Type -> Type+quantifyType' exclude c t = ForallT vs c t+  where+  vs = filter (\tvb -> D.tvName tvb `Set.notMember` exclude)+     $ D.changeTVFlags D.SpecifiedSpec+     $ D.freeVariablesWellScoped (t:c) -- stable order++-- | Convert a 'TyVarBndr' into its corresponding 'Type'.+tvbToType :: D.TyVarBndr_ flag -> Type+tvbToType = D.elimTV VarT (SigT . VarT)++-- | Peel off a kind signature from a Type (if it has one).+unSigT :: Type -> Type+unSigT (SigT t _) = t+unSigT t          = t++isDataFamily :: D.DatatypeVariant -> Bool+isDataFamily D.Datatype        = False+isDataFamily D.Newtype         = False+isDataFamily D.DataInstance    = True+isDataFamily D.NewtypeInstance = True+#if MIN_VERSION_th_abstraction(0,5,0)+isDataFamily D.TypeData        = False+#endif++#if !(MIN_VERSION_template_haskell(2,21,0)) && !(MIN_VERSION_th_abstraction(0,6,0))+type TyVarBndrVis = D.TyVarBndr_ ()++bndrReq :: ()+bndrReq = ()+#endif++------------------------------------------------------------------------+-- TH-quoted names+------------------------------------------------------------------------+-- Note that this module only TemplateHaskellQuotes, not TemplateHaskell,+-- which makes lens able to be used in stage1 cross-compilers.++traversalTypeName      :: Name+traversalTypeName       = ''Traversal++traversal'TypeName     :: Name+traversal'TypeName      = ''Traversal'++lensTypeName           :: Name+lensTypeName            = ''Lens++lens'TypeName          :: Name+lens'TypeName           = ''Lens'++isoTypeName            :: Name+isoTypeName             = ''Iso++iso'TypeName           :: Name+iso'TypeName            = ''Iso'++getterTypeName         :: Name+getterTypeName          = ''Getter++foldTypeName           :: Name+foldTypeName            = ''Fold++prismTypeName          :: Name+prismTypeName           = ''Prism++prism'TypeName         :: Name+prism'TypeName          = ''Prism'++reviewTypeName          :: Name+reviewTypeName           = ''Review++wrappedTypeName         :: Name+wrappedTypeName          = ''Wrapped++unwrappedTypeName       :: Name+unwrappedTypeName        = ''Unwrapped++rewrappedTypeName       :: Name+rewrappedTypeName        = ''Rewrapped++_wrapped'ValName        :: Name+_wrapped'ValName         = '_Wrapped'++isoValName              :: Name+isoValName               = 'iso++prismValName            :: Name+prismValName             = 'prism++untoValName             :: Name+untoValName              = 'unto++phantomValName          :: Name+phantomValName           = 'phantom2++phantom2 :: (Functor f, Contravariant f) => f a -> f b+phantom2 = phantom+{-# INLINE phantom2 #-}++composeValName          :: Name+composeValName           = '(.)++idValName               :: Name+idValName                = 'id++fmapValName             :: Name+fmapValName              = 'fmap++pureValName             :: Name+pureValName              = 'pure++apValName               :: Name+apValName                = '(<*>)++rightDataName           :: Name+rightDataName            = 'Right++leftDataName            :: Name+leftDataName             = 'Left+++------------------------------------------------------------------------+-- Support for generating inline pragmas+------------------------------------------------------------------------++inlinePragma :: Name -> [DecQ]+inlinePragma methodName = [pragInlD methodName Inline FunLike AllPhases]
+ src/Control/Lens/Internal/Zoom.hs view
@@ -0,0 +1,335 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE Trustworthy #-}++{-# OPTIONS_GHC -Wno-orphans -Wno-warnings-deprecations #-}+-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Internal.Zoom+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+----------------------------------------------------------------------------+module Control.Lens.Internal.Zoom+  (+  -- * Zoom+    Focusing(..)+  , FocusingWith(..)+  , FocusingPlus(..)+  , FocusingOn(..)+  , FocusingMay(..), May(..)+  , FocusingErr(..), Err(..)+  , FocusingFree(..), Freed(..)+  -- * Magnify+  , Effect(..)+  , EffectRWS(..)+  ) where++import Prelude ()++import Control.Lens.Internal.Prelude+import Control.Monad+import Control.Monad.Trans.Free+import Data.Functor.Bind++------------------------------------------------------------------------------+-- Focusing+------------------------------------------------------------------------------++-- | Used by 'Control.Lens.Zoom.Zoom' to 'Control.Lens.Zoom.zoom' into 'Control.Monad.State.StateT'.+newtype Focusing m s a = Focusing { unfocusing :: m (s, a) }++instance Monad m => Functor (Focusing m s) where+  fmap f (Focusing m) = Focusing $ do+     (s, a) <- m+     return (s, f a)+  {-# INLINE fmap #-}++instance (Monad m, Semigroup s) => Apply (Focusing m s) where+  Focusing mf <.> Focusing ma = Focusing $ do+    (s, f) <- mf+    (s', a) <- ma+    return (s <> s', f a)+  {-# INLINE (<.>) #-}++instance (Monad m, Monoid s) => Applicative (Focusing m s) where+  pure a = Focusing (return (mempty, a))+  {-# INLINE pure #-}+  Focusing mf <*> Focusing ma = Focusing $ do+    (s, f) <- mf+    (s', a) <- ma+    return (mappend s s', f a)+  {-# INLINE (<*>) #-}++------------------------------------------------------------------------------+-- FocusingWith+------------------------------------------------------------------------------++-- | Used by 'Control.Lens.Zoom.Zoom' to 'Control.Lens.Zoom.zoom' into 'Control.Monad.RWS.RWST'.+newtype FocusingWith w m s a = FocusingWith { unfocusingWith :: m (s, a, w) }++instance Monad m => Functor (FocusingWith w m s) where+  fmap f (FocusingWith m) = FocusingWith $ do+     (s, a, w) <- m+     return (s, f a, w)+  {-# INLINE fmap #-}++instance (Monad m, Semigroup s, Semigroup w) => Apply (FocusingWith w m s) where+  FocusingWith mf <.> FocusingWith ma = FocusingWith $ do+    (s, f, w) <- mf+    (s', a, w') <- ma+    return (s <> s', f a, w <> w')+  {-# INLINE (<.>) #-}++instance (Monad m, Monoid s, Monoid w) => Applicative (FocusingWith w m s) where+  pure a = FocusingWith (return (mempty, a, mempty))+  {-# INLINE pure #-}+  FocusingWith mf <*> FocusingWith ma = FocusingWith $ do+    (s, f, w) <- mf+    (s', a, w') <- ma+    return (mappend s s', f a, mappend w w')+  {-# INLINE (<*>) #-}++------------------------------------------------------------------------------+-- FocusingPlus+------------------------------------------------------------------------------++-- | Used by 'Control.Lens.Zoom.Zoom' to 'Control.Lens.Zoom.zoom' into 'Control.Monad.Writer.WriterT'.+newtype FocusingPlus w k s a = FocusingPlus { unfocusingPlus :: k (s, w) a }++instance Functor (k (s, w)) => Functor (FocusingPlus w k s) where+  fmap f (FocusingPlus as) = FocusingPlus (fmap f as)+  {-# INLINE fmap #-}++instance Apply (k (s, w)) => Apply (FocusingPlus w k s) where+  FocusingPlus kf <.> FocusingPlus ka = FocusingPlus (kf <.> ka)+  {-# INLINE (<.>) #-}++instance Applicative (k (s, w)) => Applicative (FocusingPlus w k s) where+  pure = FocusingPlus . pure+  {-# INLINE pure #-}+  FocusingPlus kf <*> FocusingPlus ka = FocusingPlus (kf <*> ka)+  {-# INLINE (<*>) #-}++------------------------------------------------------------------------------+-- FocusingOn+------------------------------------------------------------------------------++-- | Used by 'Control.Lens.Zoom.Zoom' to 'Control.Lens.Zoom.zoom' into 'Control.Monad.Trans.Maybe.MaybeT' or 'Control.Monad.Trans.List.ListT'.+newtype FocusingOn f k s a = FocusingOn { unfocusingOn :: k (f s) a }++instance Functor (k (f s)) => Functor (FocusingOn f k s) where+  fmap f (FocusingOn as) = FocusingOn (fmap f as)+  {-# INLINE fmap #-}++instance Apply (k (f s)) => Apply (FocusingOn f k s) where+  FocusingOn kf <.> FocusingOn ka = FocusingOn (kf <.> ka)+  {-# INLINE (<.>) #-}++instance Applicative (k (f s)) => Applicative (FocusingOn f k s) where+  pure = FocusingOn . pure+  {-# INLINE pure #-}+  FocusingOn kf <*> FocusingOn ka = FocusingOn (kf <*> ka)+  {-# INLINE (<*>) #-}++------------------------------------------------------------------------------+-- May+------------------------------------------------------------------------------++-- | Make a 'Monoid' out of 'Maybe' for error handling.+newtype May a = May { getMay :: Maybe a }++instance Semigroup a => Semigroup (May a) where+  May Nothing <> _ = May Nothing+  _ <> May Nothing = May Nothing+  May (Just a) <> May (Just b) = May (Just (a <> b))+  {-# INLINE (<>) #-}++instance Monoid a => Monoid (May a) where+  mempty = May (Just mempty)+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  May Nothing `mappend` _ = May Nothing+  _ `mappend` May Nothing = May Nothing+  May (Just a) `mappend` May (Just b) = May (Just (mappend a b))+  {-# INLINE mappend #-}+#endif++------------------------------------------------------------------------------+-- FocusingMay+------------------------------------------------------------------------------++-- | Used by 'Control.Lens.Zoom.Zoom' to 'Control.Lens.Zoom.zoom' into 'Control.Monad.Error.ErrorT'.+newtype FocusingMay k s a = FocusingMay { unfocusingMay :: k (May s) a }++instance Functor (k (May s)) => Functor (FocusingMay k s) where+  fmap f (FocusingMay as) = FocusingMay (fmap f as)+  {-# INLINE fmap #-}++instance Apply (k (May s)) => Apply (FocusingMay k s) where+  FocusingMay kf <.> FocusingMay ka = FocusingMay (kf <.> ka)+  {-# INLINE (<.>) #-}++instance Applicative (k (May s)) => Applicative (FocusingMay k s) where+  pure = FocusingMay . pure+  {-# INLINE pure #-}+  FocusingMay kf <*> FocusingMay ka = FocusingMay (kf <*> ka)+  {-# INLINE (<*>) #-}++------------------------------------------------------------------------------+-- Err+------------------------------------------------------------------------------++-- | Make a 'Monoid' out of 'Either' for error handling.+newtype Err e a = Err { getErr :: Either e a }++instance Semigroup a => Semigroup (Err e a) where+  Err (Left e) <> _ = Err (Left e)+  _ <> Err (Left e) = Err (Left e)+  Err (Right a) <> Err (Right b) = Err (Right (a <> b))+  {-# INLINE (<>) #-}++instance Monoid a => Monoid (Err e a) where+  mempty = Err (Right mempty)+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  Err (Left e) `mappend` _ = Err (Left e)+  _ `mappend` Err (Left e) = Err (Left e)+  Err (Right a) `mappend` Err (Right b) = Err (Right (mappend a b))+  {-# INLINE mappend #-}+#endif++------------------------------------------------------------------------------+-- FocusingErr+------------------------------------------------------------------------------++-- | Used by 'Control.Lens.Zoom.Zoom' to 'Control.Lens.Zoom.zoom' into 'Control.Monad.Error.ErrorT'.+newtype FocusingErr e k s a = FocusingErr { unfocusingErr :: k (Err e s) a }++instance Functor (k (Err e s)) => Functor (FocusingErr e k s) where+  fmap f (FocusingErr as) = FocusingErr (fmap f as)+  {-# INLINE fmap #-}++instance Apply (k (Err e s)) => Apply (FocusingErr e k s) where+  FocusingErr kf <.> FocusingErr ka = FocusingErr (kf <.> ka)+  {-# INLINE (<.>) #-}++instance Applicative (k (Err e s)) => Applicative (FocusingErr e k s) where+  pure = FocusingErr . pure+  {-# INLINE pure #-}+  FocusingErr kf <*> FocusingErr ka = FocusingErr (kf <*> ka)+  {-# INLINE (<*>) #-}++------------------------------------------------------------------------------+-- Freed+------------------------------------------------------------------------------++-- | Make a 'Monoid' out of 'FreeF' for result collection.++newtype Freed f m a = Freed { getFreed :: FreeF f a (FreeT f m a) }++instance (Applicative f, Semigroup a, Monad m) => Semigroup (Freed f m a) where+  Freed (Pure a) <> Freed (Pure b) = Freed $ Pure $ a <> b+  Freed (Pure a) <> Freed (Free g) = Freed $ Free $ liftA2 (liftM2 (<>)) (pure $ return a) g+  Freed (Free f) <> Freed (Pure b) = Freed $ Free $ liftA2 (liftM2 (<>)) f (pure $ return b)+  Freed (Free f) <> Freed (Free g) = Freed $ Free $ liftA2 (liftM2 (<>)) f g++instance (Applicative f, Monoid a, Monad m) => Monoid (Freed f m a) where+  mempty = Freed $ Pure mempty++#if !(MIN_VERSION_base(4,11,0))+  Freed (Pure a) `mappend` Freed (Pure b) = Freed $ Pure $ a `mappend` b+  Freed (Pure a) `mappend` Freed (Free g) = Freed $ Free $ liftA2 (liftM2 mappend) (pure $ return a) g+  Freed (Free f) `mappend` Freed (Pure b) = Freed $ Free $ liftA2 (liftM2 mappend) f (pure $ return b)+  Freed (Free f) `mappend` Freed (Free g) = Freed $ Free $ liftA2 (liftM2 mappend) f g+#endif++------------------------------------------------------------------------------+-- FocusingFree+------------------------------------------------------------------------------++-- | Used by 'Control.Lens.Zoom.Zoom' to 'Control.Lens.Zoom.zoom' into+-- 'Control.Monad.Trans.FreeT'+newtype FocusingFree f m k s a = FocusingFree { unfocusingFree :: k (Freed f m s) a }++instance Functor (k (Freed f m s)) => Functor (FocusingFree f m k s) where+  fmap f (FocusingFree as) = FocusingFree (fmap f as)+  {-# INLINE fmap #-}++instance Apply (k (Freed f m s)) => Apply (FocusingFree f m k s) where+  FocusingFree kf <.> FocusingFree ka = FocusingFree (kf <.> ka)+  {-# INLINE (<.>) #-}++instance Applicative (k (Freed f m s)) => Applicative (FocusingFree f m k s) where+  pure = FocusingFree . pure+  {-# INLINE pure #-}+  FocusingFree kf <*> FocusingFree ka = FocusingFree (kf <*> ka)+  {-# INLINE (<*>) #-}++-----------------------------------------------------------------------------+--- Effect+-------------------------------------------------------------------------------++-- | Wrap a monadic effect with a phantom type argument.+newtype Effect m r a = Effect { getEffect :: m r }+-- type role Effect representational nominal phantom++instance Functor (Effect m r) where+  fmap _ (Effect m) = Effect m+  {-# INLINE fmap #-}++instance Contravariant (Effect m r) where+  contramap _ (Effect m) = Effect m+  {-# INLINE contramap #-}++instance (Monad m, Semigroup r) => Semigroup (Effect m r a) where+  Effect ma <> Effect mb = Effect (liftM2 (<>) ma mb)+  {-# INLINE (<>) #-}++instance (Monad m, Monoid r) => Monoid (Effect m r a) where+  mempty = Effect (return mempty)+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  Effect ma `mappend` Effect mb = Effect (liftM2 mappend ma mb)+  {-# INLINE mappend #-}+#endif++instance (Apply m, Semigroup r) => Apply (Effect m r) where+  Effect ma <.> Effect mb = Effect (liftF2 (<>) ma mb)+  {-# INLINE (<.>) #-}++instance (Monad m, Monoid r) => Applicative (Effect m r) where+  pure _ = Effect (return mempty)+  {-# INLINE pure #-}+  Effect ma <*> Effect mb = Effect (liftM2 mappend ma mb)+  {-# INLINE (<*>) #-}++------------------------------------------------------------------------------+-- EffectRWS+------------------------------------------------------------------------------++-- | Wrap a monadic effect with a phantom type argument. Used when magnifying 'Control.Monad.RWS.RWST'.+newtype EffectRWS w st m s a = EffectRWS { getEffectRWS :: st -> m (s,st,w) }++instance Functor (EffectRWS w st m s) where+  fmap _ (EffectRWS m) = EffectRWS m+  {-# INLINE fmap #-}++instance (Semigroup s, Semigroup w, Bind m) => Apply (EffectRWS w st m s) where+  EffectRWS m <.> EffectRWS n = EffectRWS $ \st -> m st >>- \ (s,t,w) -> fmap (\(s',u,w') -> (s <> s', u, w <> w')) (n t)+  {-# INLINE (<.>) #-}++instance (Monoid s, Monoid w, Monad m) => Applicative (EffectRWS w st m s) where+  pure _ = EffectRWS $ \st -> return (mempty, st, mempty)+  {-# INLINE pure #-}+  EffectRWS m <*> EffectRWS n = EffectRWS $ \st -> m st >>= \ (s,t,w) -> n t >>= \ (s',u,w') -> return (mappend s s', u, mappend w w')+  {-# INLINE (<*>) #-}++instance Contravariant (EffectRWS w st m s) where+  contramap _ (EffectRWS m) = EffectRWS m+  {-# INLINE contramap #-}
src/Control/Lens/Iso.hs view
@@ -1,160 +1,578 @@+{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-}+{-# LANGUAGE Trustworthy #-}++#if __GLASGOW_HASKELL__ >= 806+{-# LANGUAGE PolyKinds #-}+#else+{-# LANGUAGE TypeInType #-}+#endif++#include "lens-common.h"+ ----------------------------------------------------------------------------- -- | -- Module      :  Control.Lens.Iso--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional--- Portability :  Rank2Types+-- Portability :  Rank2Types, TypeFamilies, FunctionalDependencies -- ---------------------------------------------------------------------------- module Control.Lens.Iso   (   -- * Isomorphism Lenses-    Iso+    Iso, Iso'+  , AnIso, AnIso'+  -- * Isomorphism Construction   , iso-  , isos-  , ala+  -- * Consuming Isomorphisms+  , from+  , cloneIso+  , withIso+  -- * Working with isomorphisms+  , au   , auf+  , xplat+  , xplatf   , under-  -- * Primitive isomorphisms-  , from-  , via-  , Isomorphism(..)-  , Isomorphic(..)+  , mapping   -- ** Common Isomorphisms-  , _const-  , identity-  -- * Storing Isomorphisms-  , ReifiedIso(..)-  -- * Simplicity-  , SimpleIso-  , SimpleReifiedIso+  , simple+  , non, non'+  , anon+  , enum+  , curried, uncurried+  , flipped+  , swapped+  , pattern Swapped+  , strict, lazy+  , pattern Strict+  , pattern Lazy+  , Reversing(..)+  , reversed+  , pattern Reversed+  , involuted+  , pattern List+  -- ** Uncommon Isomorphisms+  , magma+  , imagma+  , Magma+  -- ** Contravariant functors+  , contramapping+  -- * Profunctors+  , Profunctor(dimap,rmap,lmap)+  , dimapping+  , lmapping+  , rmapping+  -- * Bifunctors+  , bimapping+  , firsting+  , seconding+  -- * Coercions+  , coerced   ) where -import Control.Applicative-import Control.Category+import Control.Lens.Equality (simple) import Control.Lens.Getter-import Control.Lens.Internal-import Control.Lens.Isomorphic-import Control.Lens.Setter+import Control.Lens.Fold+import Control.Lens.Internal.Context+import Control.Lens.Internal.Indexed+import Control.Lens.Internal.Iso as Iso+import Control.Lens.Internal.Magma+import Control.Lens.Prism+import Control.Lens.Review import Control.Lens.Type++import Data.Bifunctor+import Data.Bifunctor.Swap (Swap (..)) import Data.Functor.Identity-import Prelude hiding ((.),id)+import Data.Strict.Classes (Strict (..))+import Data.Maybe+import Data.Profunctor+import Data.Profunctor.Unsafe +import Data.Coerce++import qualified GHC.Exts as Exts+import GHC.Exts (TYPE)+ -- $setup+-- >>> :set -XNoOverloadedStrings -- >>> import Control.Lens+-- >>> import qualified Data.Map as Map+-- >>> import Data.Foldable+-- >>> import Data.Monoid --------------------------------------------------------------------------------- Isomorphisms families as Lenses+----------------------------------------------------------------------------+-- Isomorphisms ----------------------------------------------------------------------------- --- | Isomorphim families can be composed with other lenses using either ('.') and 'id'--- from the Prelude or from Control.Category. However, if you compose them--- with each other using ('.') from the Prelude, they will be dumbed down to a--- mere 'Lens'.+-- | When you see this as an argument to a function, it expects an 'Iso'.+type AnIso s t a b = Exchange a b a (Identity b) -> Exchange a b s (Identity t)++-- | A 'Simple' 'AnIso'.+type AnIso' s a = AnIso s s a a+++-- | Build a simple isomorphism from a pair of inverse functions. -- -- @--- import Control.Category--- import Prelude hiding (('Prelude..'),'Prelude.id')+-- 'Control.Lens.Getter.view' ('iso' f g) ≡ f+-- 'Control.Lens.Getter.view' ('Control.Lens.Iso.from' ('iso' f g)) ≡ g+-- 'Control.Lens.Setter.over' ('iso' f g) h ≡ g '.' h '.' f+-- 'Control.Lens.Setter.over' ('Control.Lens.Iso.from' ('iso' f g)) h ≡ f '.' h '.' g -- @------ @type 'Iso' a b c d = forall k f. ('Isomorphic' k, 'Functor' f) => 'Overloaded' k f a b c d@-type Iso a b c d = forall k f. (Isomorphic k, Functor f) => k (c -> f d) (a -> f b)+iso :: (s -> a) -> (b -> t) -> Iso s t a b+iso sa bt = dimap sa (fmap bt)+{-# INLINE iso #-} --- |--- @type 'SimpleIso' = 'Control.Lens.Type.Simple' 'Iso'@-type SimpleIso a b = Iso a a b b+----------------------------------------------------------------------------+-- Consuming Isomorphisms+----------------------------------------------------------------------------- --- | Build an isomorphism family from two pairs of inverse functions+-- | Invert an isomorphism. -- -- @--- 'view' ('isos' ac ca bd db) ≡ ac--- 'view' ('from' ('isos' ac ca bd db)) ≡ ca--- 'set' ('isos' ac ca bd db) cd ≡ db '.' cd '.' ac--- 'set' ('from' ('isos' ac ca bd db')) ab ≡ bd '.' ab '.' ca+-- 'from' ('from' l) ≡ l -- @+from :: AnIso s t a b -> Iso b a t s+from l = withIso l $ \sa bt -> iso bt sa+{-# INLINE from #-}++-- | Extract the two functions, one from @s -> a@ and+-- one from @b -> t@ that characterize an 'Iso'.+withIso :: forall s t a b rep (r :: TYPE rep).+             AnIso s t a b -> ((s -> a) -> (b -> t) -> r) -> r+withIso ai k = case ai (Exchange id Identity) of+  Exchange sa bt -> k sa (runIdentity #. bt)+{-# INLINE withIso #-}++-- | Convert from 'AnIso' back to any 'Iso'. ----- @isos :: (a -> c) -> (c -> a) -> (b -> d) -> (d -> b) -> 'Iso' a b c d@-isos :: (Isomorphic k, Functor f) => (a -> c) -> (c -> a) -> (b -> d) -> (d -> b) -> k (c -> f d) (a -> f b)-isos ac ca bd db = isomorphic-  (\cfd a -> db <$> cfd (ac a))-  (\afb c -> bd <$> afb (ca c))-{-# INLINE isos #-}+-- This is useful when you need to store an isomorphism as a data type inside a container+-- and later reconstitute it as an overloaded function.+--+-- See 'Control.Lens.Lens.cloneLens' or 'Control.Lens.Traversal.cloneTraversal' for more information on why you might want to do this.+cloneIso :: AnIso s t a b -> Iso s t a b+cloneIso k = withIso k $ \sa bt -> iso sa bt+{-# INLINE cloneIso #-} --- | Build a simple isomorphism from a pair of inverse functions+-----------------------------------------------------------------------------+-- Isomorphisms families as Lenses+-----------------------------------------------------------------------------++-- | Based on 'Control.Lens.Wrapped.ala' from Conor McBride's work on Epigram. --+-- This version is generalized to accept any 'Iso', not just a @newtype@. --+-- >>> au (_Wrapping Sum) foldMap [1,2,3,4]+-- 10+--+-- You may want to think of this combinator as having the following, simpler type:+-- -- @--- 'view' ('iso' f g) ≡ f--- 'view' ('from' ('iso' f g)) ≡ g--- 'set' ('isos' f g) h ≡ g '.' h '.' f--- 'set' ('from' ('iso' f g')) h ≡ f '.' h '.' g+-- au :: AnIso s t a b -> ((b -> t) -> e -> s) -> e -> a -- @ ----- @iso :: (a -> b) -> (b -> a) -> 'Control.Lens.Type.Simple' 'Iso' a b@-iso :: (Isomorphic k, Functor f) => (a -> b) -> (b -> a) -> k (b -> f b) (a -> f a)-iso ab ba = isos ab ba ab ba-{-# INLINE iso #-}+-- @+-- au = xplat . from+-- @+au :: Functor f => AnIso s t a b -> ((b -> t) -> f s) -> f a+au k = withIso k $ \ sa bt f -> fmap sa (f bt)+{-# INLINE au #-} --- | Based on @ala@ from Conor McBride's work on Epigram.+-- | Based on @ala'@ from Conor McBride's work on Epigram. ----- >>> :m + Data.Monoid.Lens Data.Foldable--- >>> ala _sum foldMap [1,2,3,4]+-- This version is generalized to accept any 'Iso', not just a @newtype@.+--+-- For a version you pass the name of the @newtype@ constructor to, see 'Control.Lens.Wrapped.alaf'.+--+-- >>> auf (_Wrapping Sum) (foldMapOf both) Prelude.length ("hello","world") -- 10-ala :: Simple Iso a b -> ((a -> b) -> c -> b) -> c -> a-ala l f e = f (view l) e ^. from l-{-# INLINE ala #-}---- |--- Based on @ala'@ from Conor McBride's work on Epigram. -- -- Mnemonically, the German /auf/ plays a similar role to /à la/, and the combinator--- is 'ala' with an extra function argument.-auf :: Simple Iso a b -> ((d -> b) -> c -> b) -> (d -> a) -> c -> a-auf l f g e = f (view l . g) e ^. from l+-- is 'au' with an extra function argument:+--+-- @+-- 'auf' :: 'Iso' s t a b -> ((r -> t) -> e -> s) -> (r -> b) -> e -> a+-- @+--+-- but the signature is general.+--+-- Note: The direction of the 'Iso' required for this function changed in @lens@ 4.18 to match up+-- with the behavior of 'au'. For the old behavior use 'xplatf' or for a version that is compatible+-- across both old and new versions of @lens@ you can just use 'coerce'!+auf :: (Functor f, Functor g) => AnIso s t a b -> (f t -> g s) -> f b -> g a+auf k ftgs fb = withIso k $ \sa bt -> sa <$> ftgs (bt <$> fb) {-# INLINE auf #-} --- | The opposite of working 'over' a Setter is working 'under' an Isomorphism.+-- | @'xplat' = 'au' . 'from'@ but with a nicer signature.+xplat :: Optic (Costar ((->) s)) g s t a b -> ((s -> a) -> g b) -> g t+xplat f g = xplatf f g id++-- | @'xplatf' = 'auf' . 'from'@ but with a nicer signature. ----- @'under' = 'over' '.' 'from'@+-- >>> xplatf (_Unwrapping Sum) (foldMapOf both) Prelude.length ("hello","world")+-- 10 ----- @'under' :: 'Iso' a b c d -> (a -> b) -> c -> d@-under :: Isomorphism (c -> Mutator d) (a -> Mutator b) -> (a -> b) -> c -> d-under = over . from+-- @+-- 'xplatf' :: 'Iso' s t a b -> ((r -> a) -> e -> b) -> (r -> s) -> e -> t+-- @+xplatf :: Optic (Costar f) g s t a b -> (f a -> g b) -> f s -> g t+xplatf = coerce+{-# INLINE xplat #-}++-- | The opposite of working 'Control.Lens.Setter.over' a 'Setter' is working 'under' an isomorphism.+--+-- @+-- 'under' ≡ 'Control.Lens.Setter.over' '.' 'from'+-- @+--+-- @+-- 'under' :: 'Iso' s t a b -> (t -> s) -> b -> a+-- @+under :: AnIso s t a b -> (t -> s) -> b -> a+under k = withIso k $ \ sa bt ts -> sa . ts . bt {-# INLINE under #-}  ----------------------------------------------------------------------------- -- Isomorphisms ----------------------------------------------------------------------------- --- | This isomorphism can be used to wrap or unwrap a value in 'Identity'.+-- | This isomorphism can be used to convert to or from an instance of 'Enum'. --+-- >>> LT^.from enum+-- 0+--+-- >>> 97^.enum :: Char+-- 'a'+--+-- Note: this is only an isomorphism from the numeric range actually used+-- and it is a bit of a pleasant fiction, since there are questionable+-- 'Enum' instances for 'Double', and 'Float' that exist solely for+-- @[1.0 .. 4.0]@ sugar and the instances for those and 'Integer' don't+-- cover all values in their range.+enum :: Enum a => Iso' Int a+enum = iso toEnum fromEnum+{-# INLINE enum #-}++-- | This can be used to lift any 'Iso' into an arbitrary 'Functor'.+mapping :: (Functor f, Functor g) => AnIso s t a b -> Iso (f s) (g t) (f a) (g b)+mapping k = withIso k $ \ sa bt -> iso (fmap sa) (fmap bt)+{-# INLINE mapping #-}++-- | If @v@ is an element of a type @a@, and @a'@ is @a@ sans the element @v@, then @'non' v@ is an isomorphism from+-- @'Maybe' a'@ to @a@.+-- -- @--- x^.identity ≡ 'Identity' x--- 'Identity' x '^.' 'from' 'identity' ≡ x+-- 'non' ≡ 'non'' '.' 'only' -- @-identity :: Iso a b (Identity a) (Identity b)-identity = isos Identity runIdentity Identity runIdentity-{-# INLINE identity #-}+--+-- Keep in mind this is only a real isomorphism if you treat the domain as being @'Maybe' (a sans v)@.+--+-- This is practically quite useful when you want to have a 'Data.Map.Map' where all the entries should have non-zero values.+--+-- >>> Map.fromList [("hello",1)] & at "hello" . non 0 +~ 2+-- fromList [("hello",3)]+--+-- >>> Map.fromList [("hello",1)] & at "hello" . non 0 -~ 1+-- fromList []+--+-- >>> Map.fromList [("hello",1)] ^. at "hello" . non 0+-- 1+--+-- >>> Map.fromList [] ^. at "hello" . non 0+-- 0+--+-- This combinator is also particularly useful when working with nested maps.+--+-- /e.g./ When you want to create the nested 'Data.Map.Map' when it is missing:+--+-- >>> Map.empty & at "hello" . non Map.empty . at "world" ?~ "!!!"+-- fromList [("hello",fromList [("world","!!!")])]+--+-- and when have deleting the last entry from the nested 'Data.Map.Map' mean that we+-- should delete its entry from the surrounding one:+--+-- >>> Map.fromList [("hello",Map.fromList [("world","!!!")])] & at "hello" . non Map.empty . at "world" .~ Nothing+-- fromList []+--+-- It can also be used in reverse to exclude a given value:+--+-- >>> non 0 # rem 10 4+-- Just 2+--+-- >>> non 0 # rem 10 5+-- Nothing+non :: Eq a => a -> Iso' (Maybe a) a+non a = non' $ only a+{-# INLINE non #-} --- | This isomorphism can be used to wrap or unwrap a value in 'Const'+-- | @'non'' p@ generalizes @'non' (p # ())@ to take any unit 'Prism' --+-- This function generates an isomorphism between @'Maybe' (a | 'isn't' p a)@ and @a@.+--+-- >>> Map.singleton "hello" Map.empty & at "hello" . non' _Empty . at "world" ?~ "!!!"+-- fromList [("hello",fromList [("world","!!!")])]+--+-- >>> Map.fromList [("hello",Map.fromList [("world","!!!")])] & at "hello" . non' _Empty . at "world" .~ Nothing+-- fromList []+non' :: APrism' a () -> Iso' (Maybe a) a+non' p = iso (fromMaybe def) go where+  def                           = review (clonePrism p) ()+  go b | has (clonePrism p) b   = Nothing+       | otherwise              = Just b+{-# INLINE non' #-}++-- | @'anon' a p@ generalizes @'non' a@ to take any value and a predicate.+--+-- This function assumes that @p a@ holds @'True'@ and generates an isomorphism between @'Maybe' (a | 'not' (p a))@ and @a@.+--+-- >>> Map.empty & at "hello" . anon Map.empty Map.null . at "world" ?~ "!!!"+-- fromList [("hello",fromList [("world","!!!")])]+--+-- >>> Map.fromList [("hello",Map.fromList [("world","!!!")])] & at "hello" . anon Map.empty Map.null . at "world" .~ Nothing+-- fromList []+anon :: a -> (a -> Bool) -> Iso' (Maybe a) a+anon a p = iso (fromMaybe a) go where+  go b | p b       = Nothing+       | otherwise = Just b+{-# INLINE anon #-}++-- | The canonical isomorphism for currying and uncurrying a function.+-- -- @--- x '^.' '_const' ≡ 'Const' x--- 'Const' x '^.' 'from' '_const' ≡ x+-- 'curried' = 'iso' 'curry' 'uncurry' -- @-_const :: Iso a b (Const a c) (Const b d)-_const = isos Const getConst Const getConst-{-# INLINE _const #-}+--+-- >>> (fst^.curried) 3 4+-- 3+--+-- >>> view curried fst 3 4+-- 3+curried :: Iso ((a,b) -> c) ((d,e) -> f) (a -> b -> c) (d -> e -> f)+curried = iso curry uncurry+{-# INLINE curried #-} --------------------------------------------------------------------------------- Reifying Isomorphisms------------------------------------------------------------------------------+-- | The canonical isomorphism for uncurrying and currying a function.+--+-- @+-- 'uncurried' = 'iso' 'uncurry' 'curry'+-- @+--+-- @+-- 'uncurried' = 'from' 'curried'+-- @+--+-- >>> ((+)^.uncurried) (1,2)+-- 3+uncurried :: Iso (a -> b -> c) (d -> e -> f) ((a,b) -> c) ((d,e) -> f)+uncurried = iso uncurry curry+{-# INLINE uncurried #-} --- | Useful for storing isomorphisms in containers.-newtype ReifiedIso a b c d = ReifyIso { reflectIso :: Iso a b c d }+-- | The isomorphism for flipping a function.+--+-- >>>((,)^.flipped) 1 2+-- (2,1)+flipped :: Iso (a -> b -> c) (a' -> b' -> c') (b -> a -> c) (b' -> a' -> c')+flipped = iso flip flip+{-# INLINE flipped #-} --- | @type 'SimpleReifiedIso' = 'Control.Lens.Type.Simple' 'ReifiedIso'@-type SimpleReifiedIso a b = ReifiedIso a a b b+-- |+-- @+-- 'swapped' '.' 'swapped' ≡ 'id'+-- 'first' f '.' 'swapped' = 'swapped' '.' 'second' f+-- 'second' g '.' 'swapped' = 'swapped' '.' 'first' g+-- 'bimap' f g '.' 'swapped' = 'swapped' '.' 'bimap' g f+-- @+--+-- >>> (1,2)^.swapped+-- (2,1)+swapped :: Swap p => Iso (p a b) (p c d) (p b a) (p d c)+swapped = iso swap swap+{-# INLINE swapped #-}++-- | An 'Iso' between the lazy variant of a structure and its strict+-- counterpart.+--+-- @+-- 'strict' = 'from' 'lazy'+-- @+strict :: Strict lazy strict => Iso' lazy strict+strict = iso toStrict toLazy+{-# INLINE strict #-}++pattern Strict :: Strict s t => t -> s+pattern Strict a <- (view strict -> a) where+  Strict a = review strict a++pattern Lazy :: Strict t s => t -> s+pattern Lazy a <- (view lazy -> a) where+  Lazy a = review lazy a++pattern Swapped :: Swap p => p b a -> p a b+pattern Swapped a <- (view swapped -> a) where+  Swapped a = review swapped a++pattern Reversed :: Reversing t => t -> t+pattern Reversed a <- (view reversed -> a) where+  Reversed a = review reversed a++-- | An 'Iso' between the strict variant of a structure and its lazy+-- counterpart.+--+-- @+-- 'lazy' = 'from' 'strict'+-- @+--+lazy :: Strict lazy strict => Iso' strict lazy+lazy = iso toLazy toStrict+{-# INLINE lazy #-}++-- | An 'Iso' between a list, 'ByteString', 'Text' fragment, etc. and its reversal.+--+-- >>> "live" ^. reversed+-- "evil"+--+-- >>> "live" & reversed %~ ('d':)+-- "lived"+reversed :: Reversing a => Iso' a a+reversed = involuted Iso.reversing++-- | Given a function that is its own inverse, this gives you an 'Iso' using it in both directions.+--+-- @+-- 'involuted' ≡ 'Control.Monad.join' 'iso'+-- @+--+-- >>> "live" ^. involuted reverse+-- "evil"+--+-- >>> "live" & involuted reverse %~ ('d':)+-- "lived"+involuted :: (a -> a) -> Iso' a a+involuted a = iso a a+{-# INLINE involuted #-}++pattern List :: Exts.IsList l => [Exts.Item l] -> l+pattern List a <- (Exts.toList -> a) where+  List a = Exts.fromList a++------------------------------------------------------------------------------+-- Magma+------------------------------------------------------------------------------++-- | This isomorphism can be used to inspect a 'Traversal' to see how it associates+-- the structure and it can also be used to bake the 'Traversal' into a 'Magma' so+-- that you can traverse over it multiple times.+magma :: LensLike (Mafic a b) s t a b -> Iso s u (Magma Int t b a) (Magma j u c c)+magma l = iso (runMafic `rmap` l sell) runMagma+{-# INLINE magma #-}++-- | This isomorphism can be used to inspect an 'IndexedTraversal' to see how it associates+-- the structure and it can also be used to bake the 'IndexedTraversal' into a 'Magma' so+-- that you can traverse over it multiple times with access to the original indices.+imagma :: Over (Indexed i) (Molten i a b) s t a b -> Iso s t' (Magma i t b a) (Magma j t' c c)+imagma l = iso (runMolten #. l sell) (iextract .# Molten)+{-# INLINE imagma #-}++------------------------------------------------------------------------------+-- Contravariant+------------------------------------------------------------------------------++-- | Lift an 'Iso' into a 'Contravariant' functor.+--+-- @+-- contramapping :: 'Contravariant' f => 'Iso' s t a b -> 'Iso' (f a) (f b) (f s) (f t)+-- contramapping :: 'Contravariant' f => 'Iso'' s a -> 'Iso'' (f a) (f s)+-- @+contramapping :: Contravariant f => AnIso s t a b -> Iso (f a) (f b) (f s) (f t)+contramapping f = withIso f $ \ sa bt -> iso (contramap sa) (contramap bt)+{-# INLINE contramapping #-}++------------------------------------------------------------------------------+-- Profunctor+------------------------------------------------------------------------------++-- | Lift two 'Iso's into both arguments of a 'Profunctor' simultaneously.+--+-- @+-- dimapping :: 'Profunctor' p => 'Iso' s t a b -> 'Iso' s' t' a' b' -> 'Iso' (p a s') (p b t') (p s a') (p t b')+-- dimapping :: 'Profunctor' p => 'Iso'' s a -> 'Iso'' s' a' -> 'Iso'' (p a s') (p s a')+-- @+dimapping :: (Profunctor p, Profunctor q) => AnIso s t a b -> AnIso s' t' a' b' -> Iso (p a s') (q b t') (p s a') (q t b')+dimapping f g = withIso f $ \ sa bt -> withIso g $ \ s'a' b't' ->+  iso (dimap sa s'a') (dimap bt b't')+{-# INLINE dimapping #-}++-- | Lift an 'Iso' contravariantly into the left argument of a 'Profunctor'.+--+-- @+-- lmapping :: 'Profunctor' p => 'Iso' s t a b -> 'Iso' (p a x) (p b y) (p s x) (p t y)+-- lmapping :: 'Profunctor' p => 'Iso'' s a -> 'Iso'' (p a x) (p s x)+-- @+lmapping :: (Profunctor p, Profunctor q) => AnIso s t a b -> Iso (p a x) (q b y) (p s x) (q t y)+lmapping f = withIso f $ \ sa bt -> iso (lmap sa) (lmap bt)+{-# INLINE lmapping #-}++-- | Lift an 'Iso' covariantly into the right argument of a 'Profunctor'.+--+-- @+-- rmapping :: 'Profunctor' p => 'Iso' s t a b -> 'Iso' (p x s) (p y t) (p x a) (p y b)+-- rmapping :: 'Profunctor' p => 'Iso'' s a -> 'Iso'' (p x s) (p x a)+-- @+rmapping :: (Profunctor p, Profunctor q) => AnIso s t a b -> Iso (p x s) (q y t) (p x a) (q y b)+rmapping g = withIso g $ \ sa bt -> iso (rmap sa) (rmap bt)+{-# INLINE rmapping #-}++------------------------------------------------------------------------------+-- Bifunctor+------------------------------------------------------------------------------++-- | Lift two 'Iso's into both arguments of a 'Bifunctor'.+--+-- @+-- bimapping :: 'Bifunctor' p => 'Iso' s t a b -> 'Iso' s' t' a' b' -> 'Iso' (p s s') (p t t') (p a a') (p b b')+-- bimapping :: 'Bifunctor' p => 'Iso'' s a -> 'Iso'' s' a' -> 'Iso'' (p s s') (p a a')+-- @+bimapping :: (Bifunctor f, Bifunctor g) => AnIso s t a b -> AnIso s' t' a' b' -> Iso (f s s') (g t t') (f a a') (g b b')+bimapping f g = withIso f $ \ sa bt -> withIso g $ \s'a' b't' ->+  iso (bimap sa s'a') (bimap bt b't')+{-# INLINE bimapping #-}++-- | Lift an 'Iso' into the first argument of a 'Bifunctor'.+--+-- @+-- firsting :: 'Bifunctor' p => 'Iso' s t a b -> 'Iso' (p s x) (p t y) (p a x) (p b y)+-- firsting :: 'Bifunctor' p => 'Iso'' s a -> 'Iso'' (p s x) (p a x)+-- @+firsting :: (Bifunctor f, Bifunctor g) => AnIso s t a b -> Iso (f s x) (g t y) (f a x) (g b y)+firsting p = withIso p $ \ sa bt -> iso (first sa) (first bt)+{-# INLINE firsting #-}++-- | Lift an 'Iso' into the second argument of a 'Bifunctor'. This is+-- essentially the same as 'mapping', but it takes a 'Bifunctor p'+-- constraint instead of a 'Functor (p a)' one.+--+-- @+-- seconding :: 'Bifunctor' p => 'Iso' s t a b -> 'Iso' (p x s) (p y t) (p x a) (p y b)+-- seconding :: 'Bifunctor' p => 'Iso'' s a -> 'Iso'' (p x s) (p x a)+-- @+seconding :: (Bifunctor f, Bifunctor g) => AnIso s t a b -> Iso (f x s) (g y t) (f x a) (g y b)+seconding p = withIso p $ \ sa bt -> iso (second sa) (second bt)+{-# INLINE seconding #-}++-- | Data types that are representationally equal are isomorphic.+--+-- This is only available on GHC 7.8++--+-- @since 4.13+coerced :: forall s t a b. (Coercible s a, Coercible t b) => Iso s t a b+coerced l = rmap (fmap coerce) l .# coerce+{-# INLINE coerced #-}
− src/Control/Lens/Isomorphic.hs
@@ -1,87 +0,0 @@-{-# LANGUAGE DeriveDataTypeable #-}--------------------------------------------------------------------------------- |--- Module      :  Control.Lens.Isomorphic--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  Rank2Types---------------------------------------------------------------------------------module Control.Lens.Isomorphic-  ( Isomorphic(..)-  , Isomorphism(..)-  , from-  , via-  ) where--import Control.Category-import Data.Typeable-import Prelude hiding ((.),id)--------------------------------------------------------------------------------- Isomorphism Implementation Details---------------------------------------------------------------------------------- | Used to provide overloading of isomorphism application------ This is a 'Category' with a canonical mapping to it from the--- category of isomorphisms over Haskell types.-class Category k => Isomorphic k where-  -- | Build this morphism out of an isomorphism-  ---  -- The intention is that by using 'isomorphic', you can supply both halves of an-  -- isomorphism, but k can be instantiated to @(->)@, so you can freely use-  -- the resulting isomorphism as a function.-  isomorphic :: (a -> b) -> (b -> a) -> k a b--  -- | Map a morphism in the target category using an isomorphism between morphisms-  -- in Hask.-  isomap :: ((a -> b) -> c -> d) -> ((b -> a) -> d -> c) -> k a b -> k c d--instance Isomorphic (->) where-  isomorphic = const-  {-# INLINE isomorphic #-}-  isomap = const-  {-# INLINE isomap #-}---- | A concrete data type for isomorphisms.------ This lets you place an isomorphism inside a container without using @ImpredicativeTypes@.-data Isomorphism a b = Isomorphism (a -> b) (b -> a)-  deriving Typeable--instance Category Isomorphism where-  id = Isomorphism id id-  {-# INLINE id #-}-  Isomorphism bc cb . Isomorphism ab ba = Isomorphism (bc . ab) (ba . cb)-  {-# INLINE (.) #-}--instance Isomorphic Isomorphism where-  isomorphic = Isomorphism-  {-# INLINE isomorphic #-}-  isomap abcd badc (Isomorphism ab ba) = Isomorphism (abcd ab) (badc ba)-  {-# INLINE isomap #-}---- | Invert an isomorphism.------ Note to compose an isomorphism and receive an isomorphism in turn you'll need to use--- 'Control.Category.Category'------ @'from' ('from' l) ≡ l@------ If you imported 'Control.Category..' from @Control.Category@, then:------ @'from' l '.' 'from' r ≡ 'from' (r '.' l)@-from :: Isomorphic k => Isomorphism a b -> k b a-from (Isomorphism a b) = isomorphic b a-{-# INLINE from #-}---- | Convert from an 'Isomorphism' back to any 'Isomorphic' value.------ This is useful when you need to store an isomoprhism as a data type inside a container--- and later reconstitute it as an overloaded function.-via :: Isomorphic k => Isomorphism a b -> k a b-via (Isomorphism a b) = isomorphic a b-{-# INLINE via #-}
+ src/Control/Lens/Lens.hs view
@@ -0,0 +1,1523 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE Trustworthy #-}++#if __GLASGOW_HASKELL__ >= 806+{-# LANGUAGE PolyKinds #-}+#else+{-# LANGUAGE TypeInType #-}+#endif++#include "lens-common.h"++-------------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Lens+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  Rank2Types+--+-- A @'Lens' s t a b@ is a purely functional reference.+--+-- While a 'Control.Lens.Traversal.Traversal' could be used for+-- 'Control.Lens.Getter.Getting' like a valid 'Control.Lens.Fold.Fold', it+-- wasn't a valid 'Control.Lens.Getter.Getter' as a+-- 'Control.Lens.Getter.Getter' can't require an 'Applicative' constraint.+--+-- 'Functor', however, is a constraint on both.+--+-- @+-- type 'Lens' s t a b = forall f. 'Functor' f => (a -> f b) -> s -> f t+-- @+--+-- Every 'Lens' is a valid 'Control.Lens.Setter.Setter'.+--+-- Every 'Lens' can be used for 'Control.Lens.Getter.Getting' like a+-- 'Control.Lens.Fold.Fold' that doesn't use the 'Applicative' or+-- 'Contravariant'.+--+-- Every 'Lens' is a valid 'Control.Lens.Traversal.Traversal' that only uses+-- the 'Functor' part of the 'Applicative' it is supplied.+--+-- Every 'Lens' can be used for 'Control.Lens.Getter.Getting' like a valid+-- 'Control.Lens.Getter.Getter'.+--+-- Since every 'Lens' can be used for 'Control.Lens.Getter.Getting' like a+-- valid 'Control.Lens.Getter.Getter' it follows that it must view exactly one element in the+-- structure.+--+-- The 'Lens' laws follow from this property and the desire for it to act like+-- a 'Data.Traversable.Traversable' when used as a+-- 'Control.Lens.Traversal.Traversal'.+--+-- In the examples below, 'getter' and 'setter' are supplied as example getters+-- and setters, and are not actual functions supplied by this package.+-------------------------------------------------------------------------------+module Control.Lens.Lens+  (+  -- * Lenses+    Lens, Lens'+  , IndexedLens, IndexedLens'+  -- ** Concrete Lenses+  , ALens, ALens'+  , AnIndexedLens, AnIndexedLens'++  -- * Combinators+  , lens, ilens, iplens, withLens+  , (%%~), (%%=)+  , (%%@~), (%%@=)+  , (<%@~), (<%@=)+  , (<<%@~), (<<%@=)+  -- ** General Purpose Combinators+  , (&), (<&>), (??)+  , (&~)+  -- * Lateral Composition+  , choosing+  , chosen+  , alongside+  , inside++  -- * Setting Functionally with Passthrough+  , (<%~), (<+~), (<-~), (<*~), (<//~)+  , (<^~), (<^^~), (<**~)+  , (<||~), (<&&~), (<<>~), (<<>:~)+  , (<<%~), (<<.~), (<<?~), (<<+~), (<<-~), (<<*~)+  , (<<//~), (<<^~), (<<^^~), (<<**~)+  , (<<||~), (<<&&~), (<<<>~), (<<<>:~)++  -- * Setting State with Passthrough+  , (<%=), (<+=), (<-=), (<*=), (<//=)+  , (<^=), (<^^=), (<**=)+  , (<||=), (<&&=), (<<>=), (<<>:=)+  , (<<%=), (<<.=), (<<?=), (<<+=), (<<-=), (<<*=)+  , (<<//=), (<<^=), (<<^^=), (<<**=)+  , (<<||=), (<<&&=), (<<<>=), (<<<>:=)+  , (<<~)++  -- * Cloning Lenses+  , cloneLens+  , cloneIndexPreservingLens+  , cloneIndexedLens++  -- * Arrow operators+  , overA++  -- * ALens Combinators+  , storing+  , (^#)+  , (#~), (#%~), (#%%~), (<#~), (<#%~)+  , (#=), (#%=), (#%%=), (<#=), (<#%=)++  -- * Common Lenses+  , devoid+  , united+  , head1, last1++  -- * Context+  , Context(..)+  , Context'+  , locus++  -- * Lens fusion+  , fusing+  ) where++import Prelude ()++import Control.Arrow+import Control.Comonad+import Control.Lens.Internal.Context+import Control.Lens.Internal.Prelude+import Control.Lens.Internal.Getter+import Control.Lens.Internal.Indexed+import Control.Lens.Type+import Control.Monad.State as State+import Data.Functor.Apply+import Data.Functor.Reverse+import Data.Functor.Yoneda+import Data.Semigroup.Traversable+import GHC.Exts (TYPE)++-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import Control.Arrow+-- >>> import Control.Monad.State+-- >>> import Data.Char (chr)+-- >>> import Data.List.NonEmpty (NonEmpty ((:|)))+-- >>> import Data.Monoid (Sum (..))+-- >>> import Data.Tree (Tree (Node))+-- >>> import Debug.SimpleReflect.Expr+-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g,h)+-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f+-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g+-- >>> let h :: Expr -> Expr -> Expr; h = Debug.SimpleReflect.Vars.h+-- >>> let getter :: Expr -> Expr; getter = fun "getter"+-- >>> let setter :: Expr -> Expr -> Expr; setter = fun "setter"++infixl 8 ^#+infixr 4 %%@~, <%@~, <<%@~, %%~, <+~, <*~, <-~, <//~, <^~, <^^~, <**~, <&&~, <||~, <<>~, <<>:~, <%~, <<%~, <<.~, <<?~, <#~, #~, #%~, <#%~, #%%~+       , <<+~, <<-~, <<*~, <<//~, <<^~, <<^^~, <<**~, <<||~, <<&&~, <<<>~, <<<>:~+infix  4 %%@=, <%@=, <<%@=, %%=, <+=, <*=, <-=, <//=, <^=, <^^=, <**=, <&&=, <||=, <<>=, <<>:=, <%=, <<%=, <<.=, <<?=, <#=, #=, #%=, <#%=, #%%=+       , <<+=, <<-=, <<*=, <<//=, <<^=, <<^^=, <<**=, <<||=, <<&&=, <<<>=, <<<>:=+infixr 2 <<~+infixl 1 ??, &~++-------------------------------------------------------------------------------+-- Lenses+-------------------------------------------------------------------------------++-- | When you see this as an argument to a function, it expects a 'Lens'.+--+-- This type can also be used when you need to store a 'Lens' in a container,+-- since it is rank-1. You can turn them back into a 'Lens' with 'cloneLens',+-- or use it directly with combinators like 'storing' and ('^#').+type ALens s t a b = LensLike (Pretext (->) a b) s t a b++-- | @+-- type 'ALens'' = 'Simple' 'ALens'+-- @+type ALens' s a = ALens s s a a++-- | When you see this as an argument to a function, it expects an 'IndexedLens'+type AnIndexedLens i s t a b = Optical (Indexed i) (->) (Pretext (Indexed i) a b) s t a b++-- | @+-- type 'AnIndexedLens'' = 'Simple' ('AnIndexedLens' i)+-- @+type AnIndexedLens' i s a  = AnIndexedLens i s s a a++--------------------------+-- Constructing Lenses+--------------------------++-- | Build a 'Lens' from a getter and a setter.+--+-- @+-- 'lens' :: 'Functor' f => (s -> a) -> (s -> b -> t) -> (a -> f b) -> s -> f t+-- @+--+-- >>> s ^. lens getter setter+-- getter s+--+-- >>> s & lens getter setter .~ b+-- setter s b+--+-- >>> s & lens getter setter %~ f+-- setter s (f (getter s))+--+-- @+-- 'lens' :: (s -> a) -> (s -> a -> s) -> 'Lens'' s a+-- @+lens :: (s -> a) -> (s -> b -> t) -> Lens s t a b+lens sa sbt afb s = sbt s <$> afb (sa s)+{-# INLINE lens #-}++-- | Obtain a getter and a setter from a lens, reversing 'lens'.+withLens :: forall s t a b rep (r :: TYPE rep).+            ALens s t a b -> ((s -> a) -> (s -> b -> t) -> r) -> r+withLens l f = f (^# l) (flip (storing l))+{-# INLINE withLens #-}++-- | Build an index-preserving 'Lens' from a 'Control.Lens.Getter.Getter' and a+-- 'Control.Lens.Setter.Setter'.+iplens :: (s -> a) -> (s -> b -> t) -> IndexPreservingLens s t a b+iplens sa sbt pafb = cotabulate $ \ws -> sbt (extract ws) <$> cosieve pafb (sa <$> ws)+{-# INLINE iplens #-}++-- | Build an 'IndexedLens' from a 'Control.Lens.Getter.Getter' and+-- a 'Control.Lens.Setter.Setter'.+ilens :: (s -> (i, a)) -> (s -> b -> t) -> IndexedLens i s t a b+ilens sia sbt iafb s = sbt s <$> uncurry (indexed iafb) (sia s)+{-# INLINE ilens #-}++-- | This can be used to chain lens operations using @op=@ syntax+-- rather than @op~@ syntax for simple non-type-changing cases.+--+-- >>> (10,20) & _1 .~ 30 & _2 .~ 40+-- (30,40)+--+-- >>> (10,20) &~ do _1 .= 30; _2 .= 40+-- (30,40)+--+-- This does not support type-changing assignment, /e.g./+--+-- >>> (10,20) & _1 .~ "hello"+-- ("hello",20)+(&~) :: s -> State s a -> s+s &~ l = execState l s+{-# INLINE (&~) #-}++-- | ('%%~') can be used in one of two scenarios:+--+-- When applied to a 'Lens', it can edit the target of the 'Lens' in a+-- structure, extracting a functorial result.+--+-- When applied to a 'Traversal', it can edit the+-- targets of the traversals, extracting an applicative summary of its+-- actions.+--+-- >>> [66,97,116,109,97,110] & each %%~ \a -> ("na", chr a)+-- ("nananananana","Batman")+--+-- For all that the definition of this combinator is just:+--+-- @+-- ('%%~') ≡ 'id'+-- @+--+-- It may be beneficial to think about it as if it had these even more+-- restricted types, however:+--+-- @+-- ('%%~') :: 'Functor' f =>     'Control.Lens.Iso.Iso' s t a b       -> (a -> f b) -> s -> f t+-- ('%%~') :: 'Functor' f =>     'Lens' s t a b      -> (a -> f b) -> s -> f t+-- ('%%~') :: 'Applicative' f => 'Control.Lens.Traversal.Traversal' s t a b -> (a -> f b) -> s -> f t+-- @+--+-- When applied to a 'Traversal', it can edit the+-- targets of the traversals, extracting a supplemental monoidal summary+-- of its actions, by choosing @f = ((,) m)@+--+-- @+-- ('%%~') ::             'Control.Lens.Iso.Iso' s t a b       -> (a -> (r, b)) -> s -> (r, t)+-- ('%%~') ::             'Lens' s t a b      -> (a -> (r, b)) -> s -> (r, t)+-- ('%%~') :: 'Monoid' m => 'Control.Lens.Traversal.Traversal' s t a b -> (a -> (m, b)) -> s -> (m, t)+-- @+(%%~) :: LensLike f s t a b -> (a -> f b) -> s -> f t+(%%~) = id+{-# INLINE (%%~) #-}++-- | Modify the target of a 'Lens' in the current state returning some extra+-- information of type @r@ or modify all targets of a+-- 'Control.Lens.Traversal.Traversal' in the current state, extracting extra+-- information of type @r@ and return a monoidal summary of the changes.+--+-- >>> runState (_1 %%= \x -> (f x, g x)) (a,b)+-- (f a,(g a,b))+--+-- @+-- ('%%=') ≡ ('state' '.')+-- @+--+-- It may be useful to think of ('%%='), instead, as having either of the+-- following more restricted type signatures:+--+-- @+-- ('%%=') :: 'MonadState' s m             => 'Control.Lens.Iso.Iso' s s a b       -> (a -> (r, b)) -> m r+-- ('%%=') :: 'MonadState' s m             => 'Lens' s s a b      -> (a -> (r, b)) -> m r+-- ('%%=') :: ('MonadState' s m, 'Monoid' r) => 'Control.Lens.Traversal.Traversal' s s a b -> (a -> (r, b)) -> m r+-- @+(%%=) :: MonadState s m => Over p ((,) r) s s a b -> p a (r, b) -> m r+l %%= f = State.state (l f)+{-# INLINE (%%=) #-}++-------------------------------------------------------------------------------+-- General Purpose Combinators+-------------------------------------------------------------------------------++-- | This is convenient to 'flip' argument order of composite functions defined as:+--+-- @+-- fab ?? a = fmap ($ a) fab+-- @+--+-- For the 'Functor' instance @f = ((->) r)@ you can reason about this function as if the definition was @('??') ≡ 'flip'@:+--+-- >>> (h ?? x) a+-- h a x+--+-- >>> execState ?? [] $ modify (1:)+-- [1]+--+-- >>> over _2 ?? ("hello","world") $ length+-- ("hello",5)+--+-- >>> over ?? length ?? ("hello","world") $ _2+-- ("hello",5)+(??) :: Functor f => f (a -> b) -> a -> f b+fab ?? a = fmap ($ a) fab+{-# INLINE (??) #-}++-------------------------------------------------------------------------------+-- Common Lenses+-------------------------------------------------------------------------------++-- | Lift a 'Lens' so it can run under a function (or other corepresentable profunctor).+--+-- @+-- 'inside' :: 'Lens' s t a b -> 'Lens' (e -> s) (e -> t) (e -> a) (e -> b)+-- @+--+--+-- >>> (\x -> (x-1,x+1)) ^. inside _1 $ 5+-- 4+--+-- >>> runState (modify (1:) >> modify (2:)) ^. (inside _2) $ []+-- [2,1]+inside :: Corepresentable p => ALens s t a b -> Lens (p e s) (p e t) (p e a) (p e b)+inside l f es = o <$> f i where+  i = cotabulate $ \ e -> ipos $ l sell (cosieve es e)+  o ea = cotabulate $ \ e -> ipeek (cosieve ea e) $ l sell (cosieve es e)+{-# INLINE inside #-}++{-+-- | Lift a 'Lens' so it can run under a function (or any other corepresentable functor).+insideF :: F.Representable f => ALens s t a b -> Lens (f s) (f t) (f a) (f b)+insideF l f es = o <$> f i where+  i = F.tabulate $ \e -> ipos $ l sell (F.index es e)+  o ea = F.tabulate $ \ e -> ipeek (F.index ea e) $ l sell (F.index es e)+{-# INLINE inside #-}+-}++-- | Merge two lenses, getters, setters, folds or traversals.+--+-- @+-- 'chosen' ≡ 'choosing' 'id' 'id'+-- @+--+-- @+-- 'choosing' :: 'Control.Lens.Getter.Getter' s a     -> 'Control.Lens.Getter.Getter' s' a     -> 'Control.Lens.Getter.Getter' ('Either' s s') a+-- 'choosing' :: 'Control.Lens.Fold.Fold' s a       -> 'Control.Lens.Fold.Fold' s' a       -> 'Control.Lens.Fold.Fold' ('Either' s s') a+-- 'choosing' :: 'Lens'' s a      -> 'Lens'' s' a      -> 'Lens'' ('Either' s s') a+-- 'choosing' :: 'Control.Lens.Traversal.Traversal'' s a -> 'Control.Lens.Traversal.Traversal'' s' a -> 'Control.Lens.Traversal.Traversal'' ('Either' s s') a+-- 'choosing' :: 'Control.Lens.Setter.Setter'' s a    -> 'Control.Lens.Setter.Setter'' s' a    -> 'Control.Lens.Setter.Setter'' ('Either' s s') a+-- @+choosing :: Functor f+       => LensLike f s t a b+       -> LensLike f s' t' a b+       -> LensLike f (Either s s') (Either t t') a b+choosing l _ f (Left a)   = Left <$> l f a+choosing _ r f (Right a') = Right <$> r f a'+{-# INLINE choosing #-}++-- | This is a 'Lens' that updates either side of an 'Either', where both sides have the same type.+--+-- @+-- 'chosen' ≡ 'choosing' 'id' 'id'+-- @+--+-- >>> Left a^.chosen+-- a+--+-- >>> Right a^.chosen+-- a+--+-- >>> Right "hello"^.chosen+-- "hello"+--+-- >>> Right a & chosen *~ b+-- Right (a * b)+--+-- @+-- 'chosen' :: 'Lens' ('Either' a a) ('Either' b b) a b+-- 'chosen' f ('Left' a)  = 'Left' '<$>' f a+-- 'chosen' f ('Right' a) = 'Right' '<$>' f a+-- @+chosen :: IndexPreservingLens (Either a a) (Either b b) a b+chosen pafb = cotabulate $ \weaa -> cosieve (either id id `lmap` pafb) weaa <&> \b -> case extract weaa of+  Left _  -> Left  b+  Right _ -> Right b+{-# INLINE chosen #-}++-- | 'alongside' makes a 'Lens' from two other lenses or a 'Getter' from two other getters+-- by executing them on their respective halves of a product.+--+-- >>> (Left a, Right b)^.alongside chosen chosen+-- (a,b)+--+-- >>> (Left a, Right b) & alongside chosen chosen .~ (c,d)+-- (Left c,Right d)+--+-- @+-- 'alongside' :: 'Lens'   s t a b -> 'Lens'   s' t' a' b' -> 'Lens'   (s,s') (t,t') (a,a') (b,b')+-- 'alongside' :: 'Getter' s   a   -> 'Getter' s'    a'    -> 'Getter' (s,s')        (a,a')+-- @+alongside :: LensLike (AlongsideLeft f b') s  t  a  b+          -> LensLike (AlongsideRight f t) s' t' a' b'+          -> LensLike f (s, s') (t, t') (a, a') (b, b')+alongside l1 l2 f (a1, a2)+  = getAlongsideRight $ l2 ?? a2 $ \b2 -> AlongsideRight+  $ getAlongsideLeft  $ l1 ?? a1 $ \b1 -> AlongsideLeft+  $ f (b1,b2)+{-# INLINE alongside #-}++-- | This 'Lens' lets you 'view' the current 'pos' of any indexed+-- store comonad and 'seek' to a new position. This reduces the API+-- for working these instances to a single 'Lens'.+--+-- @+-- 'ipos' w ≡ w 'Control.Lens.Getter.^.' 'locus'+-- 'iseek' s w ≡ w '&' 'locus' 'Control.Lens.Setter..~' s+-- 'iseeks' f w ≡ w '&' 'locus' 'Control.Lens.Setter.%~' f+-- @+--+-- @+-- 'locus' :: 'Lens'' ('Context'' a s) a+-- 'locus' :: 'Conjoined' p => 'Lens'' ('Pretext'' p a s) a+-- 'locus' :: 'Conjoined' p => 'Lens'' ('PretextT'' p g a s) a+-- @+locus :: IndexedComonadStore p => Lens (p a c s) (p b c s) a b+locus f w = (`iseek` w) <$> f (ipos w)+{-# INLINE locus #-}++-------------------------------------------------------------------------------+-- Cloning Lenses+-------------------------------------------------------------------------------++-- | Cloning a 'Lens' is one way to make sure you aren't given+-- something weaker, such as a 'Control.Lens.Traversal.Traversal' and can be+-- used as a way to pass around lenses that have to be monomorphic in @f@.+--+-- Note: This only accepts a proper 'Lens'.+--+-- >>> let example l x = set (cloneLens l) (x^.cloneLens l + 1) x in example _2 ("hello",1,"you")+-- ("hello",2,"you")+cloneLens :: ALens s t a b -> Lens s t a b+cloneLens l afb s = runPretext (l sell s) afb+{-# INLINE cloneLens #-}++-- | Clone a 'Lens' as an 'IndexedPreservingLens' that just passes through whatever+-- index is on any 'IndexedLens', 'IndexedFold', 'IndexedGetter' or  'IndexedTraversal' it is composed with.+cloneIndexPreservingLens :: ALens s t a b -> IndexPreservingLens s t a b+cloneIndexPreservingLens l pafb = cotabulate $ \ws -> runPretext (l sell (extract ws)) $ \a -> cosieve pafb (a <$ ws)+{-# INLINE cloneIndexPreservingLens #-}++-- | Clone an 'IndexedLens' as an 'IndexedLens' with the same index.+cloneIndexedLens :: AnIndexedLens i s t a b -> IndexedLens i s t a b+cloneIndexedLens l f s = runPretext (l sell s) (Indexed (indexed f))+{-# INLINE cloneIndexedLens #-}++-------------------------------------------------------------------------------+-- Setting and Remembering+-------------------------------------------------------------------------------++-- | Modify the target of a 'Lens' and return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.%~') is more flexible.+--+-- @+-- ('<%~') ::             'Lens' s t a b      -> (a -> b) -> s -> (b, t)+-- ('<%~') ::             'Control.Lens.Iso.Iso' s t a b       -> (a -> b) -> s -> (b, t)+-- ('<%~') :: 'Monoid' b => 'Control.Lens.Traversal.Traversal' s t a b -> (a -> b) -> s -> (b, t)+-- @+(<%~) :: LensLike ((,) b) s t a b -> (a -> b) -> s -> (b, t)+l <%~ f = l $ (\t -> (t, t)) . f+{-# INLINE (<%~) #-}++-- | Increment the target of a numerically valued 'Lens' and return the result.+--+-- When you do not need the result of the addition, ('Control.Lens.Setter.+~') is more flexible.+--+-- @+-- ('<+~') :: 'Num' a => 'Lens'' s a -> a -> s -> (a, s)+-- ('<+~') :: 'Num' a => 'Control.Lens.Iso.Iso'' s a  -> a -> s -> (a, s)+-- @+(<+~) :: Num a => LensLike ((,)a) s t a a -> a -> s -> (a, t)+l <+~ a = l <%~ (+ a)+{-# INLINE (<+~) #-}++-- | Decrement the target of a numerically valued 'Lens' and return the result.+--+-- When you do not need the result of the subtraction, ('Control.Lens.Setter.-~') is more flexible.+--+-- @+-- ('<-~') :: 'Num' a => 'Lens'' s a -> a -> s -> (a, s)+-- ('<-~') :: 'Num' a => 'Control.Lens.Iso.Iso'' s a  -> a -> s -> (a, s)+-- @+(<-~) :: Num a => LensLike ((,)a) s t a a -> a -> s -> (a, t)+l <-~ a = l <%~ subtract a+{-# INLINE (<-~) #-}++-- | Multiply the target of a numerically valued 'Lens' and return the result.+--+-- When you do not need the result of the multiplication, ('Control.Lens.Setter.*~') is more+-- flexible.+--+-- @+-- ('<*~') :: 'Num' a => 'Lens'' s a -> a -> s -> (a, s)+-- ('<*~') :: 'Num' a => 'Control.Lens.Iso.Iso''  s a -> a -> s -> (a, s)+-- @+(<*~) :: Num a => LensLike ((,)a) s t a a -> a -> s -> (a, t)+l <*~ a = l <%~ (* a)+{-# INLINE (<*~) #-}++-- | Divide the target of a fractionally valued 'Lens' and return the result.+--+-- When you do not need the result of the division, ('Control.Lens.Setter.//~') is more flexible.+--+-- @+-- ('<//~') :: 'Fractional' a => 'Lens'' s a -> a -> s -> (a, s)+-- ('<//~') :: 'Fractional' a => 'Control.Lens.Iso.Iso''  s a -> a -> s -> (a, s)+-- @+(<//~) :: Fractional a => LensLike ((,)a) s t a a -> a -> s -> (a, t)+l <//~ a = l <%~ (/ a)+{-# INLINE (<//~) #-}++-- | Raise the target of a numerically valued 'Lens' to a non-negative+-- 'Integral' power and return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.^~') is more flexible.+--+-- @+-- ('<^~') :: ('Num' a, 'Integral' e) => 'Lens'' s a -> e -> s -> (a, s)+-- ('<^~') :: ('Num' a, 'Integral' e) => 'Control.Lens.Iso.Iso'' s a -> e -> s -> (a, s)+-- @+(<^~) :: (Num a, Integral e) => LensLike ((,)a) s t a a -> e -> s -> (a, t)+l <^~ e = l <%~ (^ e)+{-# INLINE (<^~) #-}++-- | Raise the target of a fractionally valued 'Lens' to an 'Integral' power+-- and return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.^^~') is more flexible.+--+-- @+-- ('<^^~') :: ('Fractional' a, 'Integral' e) => 'Lens'' s a -> e -> s -> (a, s)+-- ('<^^~') :: ('Fractional' a, 'Integral' e) => 'Control.Lens.Iso.Iso'' s a -> e -> s -> (a, s)+-- @+(<^^~) :: (Fractional a, Integral e) => LensLike ((,)a) s t a a -> e -> s -> (a, t)+l <^^~ e = l <%~ (^^ e)+{-# INLINE (<^^~) #-}++-- | Raise the target of a floating-point valued 'Lens' to an arbitrary power+-- and return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.**~') is more flexible.+--+-- @+-- ('<**~') :: 'Floating' a => 'Lens'' s a -> a -> s -> (a, s)+-- ('<**~') :: 'Floating' a => 'Control.Lens.Iso.Iso'' s a  -> a -> s -> (a, s)+-- @+(<**~) :: Floating a => LensLike ((,)a) s t a a -> a -> s -> (a, t)+l <**~ a = l <%~ (** a)+{-# INLINE (<**~) #-}++-- | Logically '||' a Boolean valued 'Lens' and return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.||~') is more flexible.+--+-- @+-- ('<||~') :: 'Lens'' s 'Bool' -> 'Bool' -> s -> ('Bool', s)+-- ('<||~') :: 'Control.Lens.Iso.Iso'' s 'Bool'  -> 'Bool' -> s -> ('Bool', s)+-- @+(<||~) :: LensLike ((,)Bool) s t Bool Bool -> Bool -> s -> (Bool, t)+l <||~ b = l <%~ (|| b)+{-# INLINE (<||~) #-}++-- | Logically '&&' a Boolean valued 'Lens' and return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.&&~') is more flexible.+--+-- @+-- ('<&&~') :: 'Lens'' s 'Bool' -> 'Bool' -> s -> ('Bool', s)+-- ('<&&~') :: 'Control.Lens.Iso.Iso'' s 'Bool'  -> 'Bool' -> s -> ('Bool', s)+-- @+(<&&~) :: LensLike ((,)Bool) s t Bool Bool -> Bool -> s -> (Bool, t)+l <&&~ b = l <%~ (&& b)+{-# INLINE (<&&~) #-}++-- | Modify the target of a 'Lens', but return the old value.+--+-- When you do not need the old value, ('Control.Lens.Setter.%~') is more flexible.+--+-- @+-- ('<<%~') ::             'Lens' s t a b      -> (a -> b) -> s -> (a, t)+-- ('<<%~') ::             'Control.Lens.Iso.Iso' s t a b       -> (a -> b) -> s -> (a, t)+-- ('<<%~') :: 'Monoid' a => 'Control.Lens.Traversal.Traversal' s t a b -> (a -> b) -> s -> (a, t)+-- @+(<<%~) :: LensLike ((,)a) s t a b -> (a -> b) -> s -> (a, t)+(<<%~) l = l . lmap (\a -> (a, a)) . second'+{-# INLINE (<<%~) #-}++-- | Replace the target of a 'Lens', but return the old value.+--+-- When you do not need the old value, ('Control.Lens.Setter..~') is more flexible.+--+-- @+-- ('<<.~') ::             'Lens' s t a b      -> b -> s -> (a, t)+-- ('<<.~') ::             'Control.Lens.Iso.Iso' s t a b       -> b -> s -> (a, t)+-- ('<<.~') :: 'Monoid' a => 'Control.Lens.Traversal.Traversal' s t a b -> b -> s -> (a, t)+-- @+(<<.~) :: LensLike ((,)a) s t a b -> b -> s -> (a, t)+l <<.~ b = l $ \a -> (a, b)+{-# INLINE (<<.~) #-}++-- | Replace the target of a 'Lens' with a 'Just' value, but return the old value.+--+-- If you do not need the old value ('Control.Lens.Setter.?~') is more flexible.+--+-- >>> import qualified Data.Map as Map+-- >>> _2.at "hello" <<?~ "world" $ (42,Map.fromList [("goodnight","gracie")])+-- (Nothing,(42,fromList [("goodnight","gracie"),("hello","world")]))+--+-- @+-- ('<<?~') :: 'Iso' s t a ('Maybe' b)       -> b -> s -> (a, t)+-- ('<<?~') :: 'Lens' s t a ('Maybe' b)      -> b -> s -> (a, t)+-- ('<<?~') :: 'Traversal' s t a ('Maybe' b) -> b -> s -> (a, t)+-- @+(<<?~) :: LensLike ((,)a) s t a (Maybe b) -> b -> s -> (a, t)+l <<?~ b = l <<.~ Just b+{-# INLINE (<<?~) #-}++-- | Increment the target of a numerically valued 'Lens' and return the old value.+--+-- When you do not need the old value, ('Control.Lens.Setter.+~') is more flexible.+--+-- >>> (a,b) & _1 <<+~ c+-- (a,(a + c,b))+--+-- >>> (a,b) & _2 <<+~ c+-- (b,(a,b + c))+--+-- @+-- ('<<+~') :: 'Num' a => 'Lens'' s a -> a -> s -> (a, s)+-- ('<<+~') :: 'Num' a => 'Iso'' s a -> a -> s -> (a, s)+-- @+(<<+~) :: Num a => LensLike' ((,) a) s a -> a -> s -> (a, s)+l <<+~ b = l $ \a -> (a, a + b)+{-# INLINE (<<+~) #-}++-- | Decrement the target of a numerically valued 'Lens' and return the old value.+--+-- When you do not need the old value, ('Control.Lens.Setter.-~') is more flexible.+--+-- >>> (a,b) & _1 <<-~ c+-- (a,(a - c,b))+--+-- >>> (a,b) & _2 <<-~ c+-- (b,(a,b - c))+--+-- @+-- ('<<-~') :: 'Num' a => 'Lens'' s a -> a -> s -> (a, s)+-- ('<<-~') :: 'Num' a => 'Iso'' s a -> a -> s -> (a, s)+-- @+(<<-~) :: Num a => LensLike' ((,) a) s a -> a -> s -> (a, s)+l <<-~ b = l $ \a -> (a, a - b)+{-# INLINE (<<-~) #-}++-- | Multiply the target of a numerically valued 'Lens' and return the old value.+--+-- When you do not need the old value, ('Control.Lens.Setter.-~') is more flexible.+--+-- >>> (a,b) & _1 <<*~ c+-- (a,(a * c,b))+--+-- >>> (a,b) & _2 <<*~ c+-- (b,(a,b * c))+--+-- @+-- ('<<*~') :: 'Num' a => 'Lens'' s a -> a -> s -> (a, s)+-- ('<<*~') :: 'Num' a => 'Iso'' s a -> a -> s -> (a, s)+-- @+(<<*~) :: Num a => LensLike' ((,) a) s a -> a -> s -> (a, s)+l <<*~ b = l $ \a -> (a, a * b)+{-# INLINE (<<*~) #-}++-- | Divide the target of a numerically valued 'Lens' and return the old value.+--+-- When you do not need the old value, ('Control.Lens.Setter.//~') is more flexible.+--+-- >>> (a,b) & _1 <<//~ c+-- (a,(a / c,b))+--+-- >>> ("Hawaii",10) & _2 <<//~ 2+-- (10.0,("Hawaii",5.0))+--+-- @+-- ('<<//~') :: Fractional a => 'Lens'' s a -> a -> s -> (a, s)+-- ('<<//~') :: Fractional a => 'Iso'' s a -> a -> s -> (a, s)+-- @+(<<//~) :: Fractional a => LensLike' ((,) a) s a -> a -> s -> (a, s)+l <<//~ b = l $ \a -> (a, a / b)+{-# INLINE (<<//~) #-}++-- | Raise the target of a numerically valued 'Lens' to a non-negative power and return the old value.+--+-- When you do not need the old value, ('Control.Lens.Setter.^~') is more flexible.+--+-- @+-- ('<<^~') :: ('Num' a, 'Integral' e) => 'Lens'' s a -> e -> s -> (a, s)+-- ('<<^~') :: ('Num' a, 'Integral' e) => 'Iso'' s a -> e -> s -> (a, s)+-- @+(<<^~) :: (Num a, Integral e) => LensLike' ((,) a) s a -> e -> s -> (a, s)+l <<^~ e = l $ \a -> (a, a ^ e)+{-# INLINE (<<^~) #-}++-- | Raise the target of a fractionally valued 'Lens' to an integral power and return the old value.+--+-- When you do not need the old value, ('Control.Lens.Setter.^^~') is more flexible.+--+-- @+-- ('<<^^~') :: ('Fractional' a, 'Integral' e) => 'Lens'' s a -> e -> s -> (a, s)+-- ('<<^^~') :: ('Fractional' a, 'Integral' e) => 'Iso'' s a -> e -> S -> (a, s)+-- @+(<<^^~) :: (Fractional a, Integral e) => LensLike' ((,) a) s a -> e -> s -> (a, s)+l <<^^~ e = l $ \a -> (a, a ^^ e)+{-# INLINE (<<^^~) #-}++-- | Raise the target of a floating-point valued 'Lens' to an arbitrary power and return the old value.+--+-- When you do not need the old value, ('Control.Lens.Setter.**~') is more flexible.+--+-- >>> (a,b) & _1 <<**~ c+-- (a,(a**c,b))+--+-- >>> (a,b) & _2 <<**~ c+-- (b,(a,b**c))+--+-- @+-- ('<<**~') :: 'Floating' a => 'Lens'' s a -> a -> s -> (a, s)+-- ('<<**~') :: 'Floating' a => 'Iso'' s a -> a -> s -> (a, s)+-- @+(<<**~) :: Floating a => LensLike' ((,) a) s a -> a -> s -> (a, s)+l <<**~ e = l $ \a -> (a, a ** e)+{-# INLINE (<<**~) #-}++-- | Logically '||' the target of a 'Bool'-valued 'Lens' and return the old value.+--+-- When you do not need the old value, ('Control.Lens.Setter.||~') is more flexible.+--+-- >>> (False,6) & _1 <<||~ True+-- (False,(True,6))+--+-- >>> ("hello",True) & _2 <<||~ False+-- (True,("hello",True))+--+-- @+-- ('<<||~') :: 'Lens'' s 'Bool' -> 'Bool' -> s -> ('Bool', s)+-- ('<<||~') :: 'Iso'' s 'Bool' -> 'Bool' -> s -> ('Bool', s)+-- @+(<<||~) :: LensLike' ((,) Bool) s Bool -> Bool -> s -> (Bool, s)+l <<||~ b = l $ \a -> (a, b || a)+{-# INLINE (<<||~) #-}++-- | Logically '&&' the target of a 'Bool'-valued 'Lens' and return the old value.+--+-- When you do not need the old value, ('Control.Lens.Setter.&&~') is more flexible.+--+-- >>> (False,6) & _1 <<&&~ True+-- (False,(False,6))+--+-- >>> ("hello",True) & _2 <<&&~ False+-- (True,("hello",False))+--+-- @+-- ('<<&&~') :: 'Lens'' s Bool -> Bool -> s -> (Bool, s)+-- ('<<&&~') :: 'Iso'' s Bool -> Bool -> s -> (Bool, s)+-- @+(<<&&~) :: LensLike' ((,) Bool) s Bool -> Bool -> s -> (Bool, s)+l <<&&~ b = l $ \a -> (a, b && a)+{-# INLINE (<<&&~) #-}++-- | Modify the target of a monoidally valued 'Lens' by using ('<>') a new value and return the old value.+--+-- When you do not need the old value, ('Control.Lens.Setter.<>~') is more flexible.+--+-- >>> (Sum a,b) & _1 <<<>~ Sum c+-- (Sum {getSum = a},(Sum {getSum = a + c},b))+--+-- >>> _2 <<<>~ ", 007" $ ("James", "Bond")+-- ("Bond",("James","Bond, 007"))+--+-- @+-- ('<<<>~') :: 'Semigroup' r => 'Lens'' s r -> r -> s -> (r, s)+-- ('<<<>~') :: 'Semigroup' r => 'Iso'' s r -> r -> s -> (r, s)+-- @+(<<<>~) :: Semigroup r => LensLike' ((,) r) s r -> r -> s -> (r, s)+l <<<>~ b = l $ \a -> (a, a <> b)+{-# INLINE (<<<>~) #-}++-------------------------------------------------------------------------------+-- Setting and Remembering State+-------------------------------------------------------------------------------++-- | Modify the target of a 'Lens' into your 'Monad''s state by a user supplied+-- function and return the result.+--+-- When applied to a 'Control.Lens.Traversal.Traversal', it this will return a monoidal summary of all of the intermediate+-- results.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.%=') is more flexible.+--+-- @+-- ('<%=') :: 'MonadState' s m             => 'Lens'' s a      -> (a -> a) -> m a+-- ('<%=') :: 'MonadState' s m             => 'Control.Lens.Iso.Iso'' s a       -> (a -> a) -> m a+-- ('<%=') :: ('MonadState' s m, 'Monoid' a) => 'Control.Lens.Traversal.Traversal'' s a -> (a -> a) -> m a+-- @+(<%=) :: MonadState s m => LensLike ((,)b) s s a b -> (a -> b) -> m b+l <%= f = l %%= (\b -> (b, b)) . f+{-# INLINE (<%=) #-}+++-- | Add to the target of a numerically valued 'Lens' into your 'Monad''s state+-- and return the result.+--+-- When you do not need the result of the addition, ('Control.Lens.Setter.+=') is more+-- flexible.+--+-- @+-- ('<+=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m a+-- ('<+=') :: ('MonadState' s m, 'Num' a) => 'Control.Lens.Iso.Iso'' s a -> a -> m a+-- @+(<+=) :: (MonadState s m, Num a) => LensLike' ((,)a) s a -> a -> m a+l <+= a = l <%= (+ a)+{-# INLINE (<+=) #-}++-- | Subtract from the target of a numerically valued 'Lens' into your 'Monad''s+-- state and return the result.+--+-- When you do not need the result of the subtraction, ('Control.Lens.Setter.-=') is more+-- flexible.+--+-- @+-- ('<-=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m a+-- ('<-=') :: ('MonadState' s m, 'Num' a) => 'Control.Lens.Iso.Iso'' s a -> a -> m a+-- @+(<-=) :: (MonadState s m, Num a) => LensLike' ((,)a) s a -> a -> m a+l <-= a = l <%= subtract a+{-# INLINE (<-=) #-}++-- | Multiply the target of a numerically valued 'Lens' into your 'Monad''s+-- state and return the result.+--+-- When you do not need the result of the multiplication, ('Control.Lens.Setter.*=') is more+-- flexible.+--+-- @+-- ('<*=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m a+-- ('<*=') :: ('MonadState' s m, 'Num' a) => 'Control.Lens.Iso.Iso'' s a -> a -> m a+-- @+(<*=) :: (MonadState s m, Num a) => LensLike' ((,)a) s a -> a -> m a+l <*= a = l <%= (* a)+{-# INLINE (<*=) #-}++-- | Divide the target of a fractionally valued 'Lens' into your 'Monad''s state+-- and return the result.+--+-- When you do not need the result of the division, ('Control.Lens.Setter.//=') is more flexible.+--+-- @+-- ('<//=') :: ('MonadState' s m, 'Fractional' a) => 'Lens'' s a -> a -> m a+-- ('<//=') :: ('MonadState' s m, 'Fractional' a) => 'Control.Lens.Iso.Iso'' s a -> a -> m a+-- @+(<//=) :: (MonadState s m, Fractional a) => LensLike' ((,)a) s a -> a -> m a+l <//= a = l <%= (/ a)+{-# INLINE (<//=) #-}++-- | Raise the target of a numerically valued 'Lens' into your 'Monad''s state+-- to a non-negative 'Integral' power and return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.^=') is more flexible.+--+-- @+-- ('<^=') :: ('MonadState' s m, 'Num' a, 'Integral' e) => 'Lens'' s a -> e -> m a+-- ('<^=') :: ('MonadState' s m, 'Num' a, 'Integral' e) => 'Control.Lens.Iso.Iso'' s a -> e -> m a+-- @+(<^=) :: (MonadState s m, Num a, Integral e) => LensLike' ((,)a) s a -> e -> m a+l <^= e = l <%= (^ e)+{-# INLINE (<^=) #-}++-- | Raise the target of a fractionally valued 'Lens' into your 'Monad''s state+-- to an 'Integral' power and return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.^^=') is more flexible.+--+-- @+-- ('<^^=') :: ('MonadState' s m, 'Fractional' b, 'Integral' e) => 'Lens'' s a -> e -> m a+-- ('<^^=') :: ('MonadState' s m, 'Fractional' b, 'Integral' e) => 'Control.Lens.Iso.Iso'' s a  -> e -> m a+-- @+(<^^=) :: (MonadState s m, Fractional a, Integral e) => LensLike' ((,)a) s a -> e -> m a+l <^^= e = l <%= (^^ e)+{-# INLINE (<^^=) #-}++-- | Raise the target of a floating-point valued 'Lens' into your 'Monad''s+-- state to an arbitrary power and return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.**=') is more flexible.+--+-- @+-- ('<**=') :: ('MonadState' s m, 'Floating' a) => 'Lens'' s a -> a -> m a+-- ('<**=') :: ('MonadState' s m, 'Floating' a) => 'Control.Lens.Iso.Iso'' s a -> a -> m a+-- @+(<**=) :: (MonadState s m, Floating a) => LensLike' ((,)a) s a -> a -> m a+l <**= a = l <%= (** a)+{-# INLINE (<**=) #-}++-- | Logically '||' a Boolean valued 'Lens' into your 'Monad''s state and return+-- the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.||=') is more flexible.+--+-- @+-- ('<||=') :: 'MonadState' s m => 'Lens'' s 'Bool' -> 'Bool' -> m 'Bool'+-- ('<||=') :: 'MonadState' s m => 'Control.Lens.Iso.Iso'' s 'Bool'  -> 'Bool' -> m 'Bool'+-- @+(<||=) :: MonadState s m => LensLike' ((,)Bool) s Bool -> Bool -> m Bool+l <||= b = l <%= (|| b)+{-# INLINE (<||=) #-}++-- | Logically '&&' a Boolean valued 'Lens' into your 'Monad''s state and return+-- the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.&&=') is more flexible.+--+-- @+-- ('<&&=') :: 'MonadState' s m => 'Lens'' s 'Bool' -> 'Bool' -> m 'Bool'+-- ('<&&=') :: 'MonadState' s m => 'Control.Lens.Iso.Iso'' s 'Bool'  -> 'Bool' -> m 'Bool'+-- @+(<&&=) :: MonadState s m => LensLike' ((,)Bool) s Bool -> Bool -> m Bool+l <&&= b = l <%= (&& b)+{-# INLINE (<&&=) #-}++-- | Modify the target of a 'Lens' into your 'Monad''s state by a user supplied+-- function and return the /old/ value that was replaced.+--+-- When applied to a 'Control.Lens.Traversal.Traversal', this will return a monoidal summary of all of the old values+-- present.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.%=') is more flexible.+--+-- @+-- ('<<%=') :: 'MonadState' s m             => 'Lens'' s a      -> (a -> a) -> m a+-- ('<<%=') :: 'MonadState' s m             => 'Control.Lens.Iso.Iso'' s a       -> (a -> a) -> m a+-- ('<<%=') :: ('MonadState' s m, 'Monoid' a) => 'Control.Lens.Traversal.Traversal'' s a -> (a -> a) -> m a+-- @+--+-- @('<<%=') :: 'MonadState' s m => 'LensLike' ((,)a) s s a b -> (a -> b) -> m a@+(<<%=) :: (Strong p, MonadState s m) => Over p ((,)a) s s a b -> p a b -> m a+l <<%= f = l %%= lmap (\a -> (a,a)) (second' f)+{-# INLINE (<<%=) #-}++-- | Replace the target of a 'Lens' into your 'Monad''s state with a user supplied+-- value and return the /old/ value that was replaced.+--+-- When applied to a 'Control.Lens.Traversal.Traversal', this will return a monoidal summary of all of the old values+-- present.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter..=') is more flexible.+--+-- @+-- ('<<.=') :: 'MonadState' s m             => 'Lens'' s a      -> a -> m a+-- ('<<.=') :: 'MonadState' s m             => 'Control.Lens.Iso.Iso'' s a       -> a -> m a+-- ('<<.=') :: ('MonadState' s m, 'Monoid' a) => 'Control.Lens.Traversal.Traversal'' s a -> a -> m a+-- @+(<<.=) :: MonadState s m => LensLike ((,)a) s s a b -> b -> m a+l <<.= b = l %%= \a -> (a,b)+{-# INLINE (<<.=) #-}++-- | Replace the target of a 'Lens' into your 'Monad''s state with 'Just' a user supplied+-- value and return the /old/ value that was replaced.+--+-- When applied to a 'Control.Lens.Traversal.Traversal', this will return a monoidal summary of all of the old values+-- present.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.?=') is more flexible.+--+-- @+-- ('<<?=') :: 'MonadState' s m             => 'Lens' s t a (Maybe b)      -> b -> m a+-- ('<<?=') :: 'MonadState' s m             => 'Control.Lens.Iso.Iso' s t a (Maybe b)       -> b -> m a+-- ('<<?=') :: ('MonadState' s m, 'Monoid' a) => 'Control.Lens.Traversal.Traversal' s t a (Maybe b) -> b -> m a+-- @+(<<?=) :: MonadState s m => LensLike ((,)a) s s a (Maybe b) -> b -> m a+l <<?= b = l <<.= Just b+{-# INLINE (<<?=) #-}++-- | Modify the target of a 'Lens' into your 'Monad''s state by adding a value+-- and return the /old/ value that was replaced.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.+=') is more flexible.+--+-- @+-- ('<<+=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m a+-- ('<<+=') :: ('MonadState' s m, 'Num' a) => 'Iso'' s a -> a -> m a+-- @+(<<+=) :: (MonadState s m, Num a) => LensLike' ((,) a) s a -> a -> m a+l <<+= n = l %%= \a -> (a, a + n)+{-# INLINE (<<+=) #-}++-- | Modify the target of a 'Lens' into your 'Monad''s state by subtracting a value+-- and return the /old/ value that was replaced.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.-=') is more flexible.+--+-- @+-- ('<<-=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m a+-- ('<<-=') :: ('MonadState' s m, 'Num' a) => 'Iso'' s a -> a -> m a+-- @+(<<-=) :: (MonadState s m, Num a) => LensLike' ((,) a) s a -> a -> m a+l <<-= n = l %%= \a -> (a, a - n)+{-# INLINE (<<-=) #-}++-- | Modify the target of a 'Lens' into your 'Monad''s state by multipling a value+-- and return the /old/ value that was replaced.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.*=') is more flexible.+--+-- @+-- ('<<*=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m a+-- ('<<*=') :: ('MonadState' s m, 'Num' a) => 'Iso'' s a -> a -> m a+-- @+(<<*=) :: (MonadState s m, Num a) => LensLike' ((,) a) s a -> a -> m a+l <<*= n = l %%= \a -> (a, a * n)+{-# INLINE (<<*=) #-}++-- | Modify the target of a 'Lens' into your 'Monad'\s state by dividing by a value+-- and return the /old/ value that was replaced.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.//=') is more flexible.+--+-- @+-- ('<<//=') :: ('MonadState' s m, 'Fractional' a) => 'Lens'' s a -> a -> m a+-- ('<<//=') :: ('MonadState' s m, 'Fractional' a) => 'Iso'' s a -> a -> m a+-- @+(<<//=) :: (MonadState s m, Fractional a) => LensLike' ((,) a) s a -> a -> m a+l <<//= n = l %%= \a -> (a, a / n)+{-# INLINE (<<//=) #-}++-- | Modify the target of a 'Lens' into your 'Monad''s state by raising it by a non-negative power+-- and return the /old/ value that was replaced.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.^=') is more flexible.+--+-- @+-- ('<<^=') :: ('MonadState' s m, 'Num' a, 'Integral' e) => 'Lens'' s a -> e -> m a+-- ('<<^=') :: ('MonadState' s m, 'Num' a, 'Integral' e) => 'Iso'' s a -> a -> m a+-- @+(<<^=) :: (MonadState s m, Num a, Integral e) => LensLike' ((,) a) s a -> e -> m a+l <<^= n = l %%= \a -> (a, a ^ n)+{-# INLINE (<<^=) #-}++-- | Modify the target of a 'Lens' into your 'Monad''s state by raising it by an integral power+-- and return the /old/ value that was replaced.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.^^=') is more flexible.+--+-- @+-- ('<<^^=') :: ('MonadState' s m, 'Fractional' a, 'Integral' e) => 'Lens'' s a -> e -> m a+-- ('<<^^=') :: ('MonadState' s m, 'Fractional' a, 'Integral' e) => 'Iso'' s a -> e -> m a+-- @+(<<^^=) :: (MonadState s m, Fractional a, Integral e) => LensLike' ((,) a) s a -> e -> m a+l <<^^= n = l %%= \a -> (a, a ^^ n)+{-# INLINE (<<^^=) #-}++-- | Modify the target of a 'Lens' into your 'Monad''s state by raising it by an arbitrary power+-- and return the /old/ value that was replaced.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.**=') is more flexible.+--+-- @+-- ('<<**=') :: ('MonadState' s m, 'Floating' a) => 'Lens'' s a -> a -> m a+-- ('<<**=') :: ('MonadState' s m, 'Floating' a) => 'Iso'' s a -> a -> m a+-- @+(<<**=) :: (MonadState s m, Floating a) => LensLike' ((,) a) s a -> a -> m a+l <<**= n = l %%= \a -> (a, a ** n)+{-# INLINE (<<**=) #-}++-- | Modify the target of a 'Lens' into your 'Monad''s state by taking its logical '||' with a value+-- and return the /old/ value that was replaced.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.||=') is more flexible.+--+-- @+-- ('<<||=') :: 'MonadState' s m => 'Lens'' s 'Bool' -> 'Bool' -> m 'Bool'+-- ('<<||=') :: 'MonadState' s m => 'Iso'' s 'Bool' -> 'Bool' -> m 'Bool'+-- @+(<<||=) :: MonadState s m => LensLike' ((,) Bool) s Bool -> Bool -> m Bool+l <<||= b = l %%= \a -> (a, a || b)+{-# INLINE (<<||=) #-}++-- | Modify the target of a 'Lens' into your 'Monad''s state by taking its logical '&&' with a value+-- and return the /old/ value that was replaced.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.&&=') is more flexible.+--+-- @+-- ('<<&&=') :: 'MonadState' s m => 'Lens'' s 'Bool' -> 'Bool' -> m 'Bool'+-- ('<<&&=') :: 'MonadState' s m => 'Iso'' s 'Bool' -> 'Bool' -> m 'Bool'+-- @+(<<&&=) :: MonadState s m => LensLike' ((,) Bool) s Bool -> Bool -> m Bool+l <<&&= b = l %%= \a -> (a, a && b)+{-# INLINE (<<&&=) #-}++-- | Modify the target of a 'Lens' into your 'Monad''s state by using ('<>')+-- and return the /old/ value that was replaced.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.<>=') is more flexible.+--+-- @+-- ('<<<>=') :: ('MonadState' s m, 'Semigroup' r) => 'Lens'' s r -> r -> m r+-- ('<<<>=') :: ('MonadState' s m, 'Semigroup' r) => 'Iso'' s r -> r -> m r+-- @+(<<<>=) :: (MonadState s m, Semigroup r) => LensLike' ((,) r) s r -> r -> m r+l <<<>= b = l %%= \a -> (a, a <> b)+{-# INLINE (<<<>=) #-}++-- | Run a monadic action, and set the target of 'Lens' to its result.+--+-- @+-- ('<<~') :: 'MonadState' s m => 'Control.Lens.Iso.Iso' s s a b   -> m b -> m b+-- ('<<~') :: 'MonadState' s m => 'Lens' s s a b  -> m b -> m b+-- @+--+-- NB: This is limited to taking an actual 'Lens' than admitting a 'Control.Lens.Traversal.Traversal' because+-- there are potential loss of state issues otherwise.+(<<~) :: MonadState s m => ALens s s a b -> m b -> m b+l <<~ mb = do+  b <- mb+  modify $ \s -> ipeek b (l sell s)+  return b+{-# INLINE (<<~) #-}++-- | ('<>') a 'Semigroup' value onto the end of the target of a 'Lens' and+-- return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.<>~') is more flexible.+(<<>~) :: Semigroup m => LensLike ((,)m) s t m m -> m -> s -> (m, t)+l <<>~ m = l <%~ (<> m)+{-# INLINE (<<>~) #-}++-- | ('<>') a 'Semigroup' value onto the end of the target of a 'Lens' into+-- your 'Monad''s state and return the result.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.<>=') is more flexible.+(<<>=) :: (MonadState s m, Semigroup r) => LensLike' ((,)r) s r -> r -> m r+l <<>= r = l <%= (<> r)+{-# INLINE (<<>=) #-}++-- | ('<>') a 'Semigroup' value onto the front of the target of a 'Lens' and+-- return the result.+-- However, unlike ('<<>~'), it is prepended to the head side.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.<>:~') is more flexible.+(<<>:~) :: Semigroup m => LensLike ((,) m) s t m m -> m -> s -> (m, t)+l <<>:~ m = l <%~ (m <>)+{-# INLINE (<<>:~) #-}++-- | ('<>') a 'Semigroup' value onto the front of the target of a 'Lens' and+-- return the /old/ result.+-- However, unlike ('<<>~'), it is prepended to the head side.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.<>:~') is more flexible.+(<<<>:~) :: Semigroup m => LensLike' ((,) m) s m -> m -> s -> (m, s)+l <<<>:~ m = l <<%~ (m <>)+{-# INLINE (<<<>:~) #-}++-- | ('<>') a 'Semigroup' value onto the front of the target of a 'Lens' into+-- your 'Monad''s state and return the result.+-- However, unlike ('<<>='), it is prepended to the head side.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.<>:=') is more flexible.+(<<>:=) :: (MonadState s m, Semigroup r) => LensLike' ((,) r) s r -> r -> m r+l <<>:= r = l <%= (r <>)+{-# INLINE (<<>:=) #-}++-- | ('<>') a 'Semigroup' value onto the front of the target of a 'Lens' into+-- your 'Monad''s state and return the /old/ result.+-- However, unlike ('<<<>='), it is prepended to the head side.+--+-- When you do not need the result of the operation, ('Control.Lens.Setter.<>:=') is more flexible.+(<<<>:=) :: (MonadState s m, Semigroup r) => LensLike' ((,) r) s r -> r -> m r+l <<<>:= r = l <<%= (r <>)+{-# INLINE (<<<>:=) #-}++------------------------------------------------------------------------------+-- Arrow operators+------------------------------------------------------------------------------++-- | 'Control.Lens.Setter.over' for Arrows.+--+-- Unlike 'Control.Lens.Setter.over', 'overA' can't accept a simple+-- 'Control.Lens.Setter.Setter', but requires a full lens, or close+-- enough.+--+-- >>> overA _1 ((+1) *** (+2)) ((1,2),6)+-- ((2,4),6)+--+-- @+-- overA :: Arrow ar => Lens s t a b -> ar a b -> ar s t+-- @+overA :: Arrow ar => LensLike (Context a b) s t a b -> ar a b -> ar s t+overA l p = arr (\s -> let (Context f a) = l sell s in (f, a))+            >>> second p+            >>> arr (uncurry id)++------------------------------------------------------------------------------+-- Indexed+------------------------------------------------------------------------------++-- | Adjust the target of an 'IndexedLens' returning the intermediate result, or+-- adjust all of the targets of an 'Control.Lens.Traversal.IndexedTraversal' and return a monoidal summary+-- along with the answer.+--+-- @+-- l '<%~' f ≡ l '<%@~' 'const' f+-- @+--+-- When you do not need access to the index then ('<%~') is more liberal in what it can accept.+--+-- If you do not need the intermediate result, you can use ('Control.Lens.Setter.%@~') or even ('Control.Lens.Setter.%~').+--+-- @+-- ('<%@~') ::             'IndexedLens' i s t a b      -> (i -> a -> b) -> s -> (b, t)+-- ('<%@~') :: 'Monoid' b => 'Control.Lens.Traversal.IndexedTraversal' i s t a b -> (i -> a -> b) -> s -> (b, t)+-- @+(<%@~) :: Over (Indexed i) ((,) b) s t a b -> (i -> a -> b) -> s -> (b, t)+l <%@~ f = l (Indexed $ \i a -> let b = f i a in (b, b))+{-# INLINE (<%@~) #-}++-- | Adjust the target of an 'IndexedLens' returning the old value, or+-- adjust all of the targets of an 'Control.Lens.Traversal.IndexedTraversal' and return a monoidal summary+-- of the old values along with the answer.+--+-- @+-- ('<<%@~') ::             'IndexedLens' i s t a b      -> (i -> a -> b) -> s -> (a, t)+-- ('<<%@~') :: 'Monoid' a => 'Control.Lens.Traversal.IndexedTraversal' i s t a b -> (i -> a -> b) -> s -> (a, t)+-- @+(<<%@~) :: Over (Indexed i) ((,) a) s t a b -> (i -> a -> b) -> s -> (a, t)+l <<%@~ f = l $ Indexed $ \i a -> second' (f i) (a,a)++{-# INLINE (<<%@~) #-}++-- | Adjust the target of an 'IndexedLens' returning a supplementary result, or+-- adjust all of the targets of an 'Control.Lens.Traversal.IndexedTraversal' and return a monoidal summary+-- of the supplementary results and the answer.+--+-- @+-- ('%%@~') ≡ 'Control.Lens.Indexed.withIndex'+-- @+--+-- @+-- ('%%@~') :: 'Functor' f => 'IndexedLens' i s t a b      -> (i -> a -> f b) -> s -> f t+-- ('%%@~') :: 'Applicative' f => 'Control.Lens.Traversal.IndexedTraversal' i s t a b -> (i -> a -> f b) -> s -> f t+-- @+--+-- In particular, it is often useful to think of this function as having one of these even more+-- restricted type signatures:+--+-- @+-- ('%%@~') ::             'IndexedLens' i s t a b      -> (i -> a -> (r, b)) -> s -> (r, t)+-- ('%%@~') :: 'Monoid' r => 'Control.Lens.Traversal.IndexedTraversal' i s t a b -> (i -> a -> (r, b)) -> s -> (r, t)+-- @+(%%@~) :: Over (Indexed i) f s t a b -> (i -> a -> f b) -> s -> f t+(%%@~) l = l .# Indexed+{-# INLINE (%%@~) #-}++-- | Adjust the target of an 'IndexedLens' returning a supplementary result, or+-- adjust all of the targets of an 'Control.Lens.Traversal.IndexedTraversal' within the current state, and+-- return a monoidal summary of the supplementary results.+--+-- @+-- l '%%@=' f ≡ 'state' (l '%%@~' f)+-- @+--+-- @+-- ('%%@=') :: 'MonadState' s m                 => 'IndexedLens' i s s a b      -> (i -> a -> (r, b)) -> s -> m r+-- ('%%@=') :: ('MonadState' s m, 'Monoid' r) => 'Control.Lens.Traversal.IndexedTraversal' i s s a b -> (i -> a -> (r, b)) -> s -> m r+-- @+(%%@=) :: MonadState s m => Over (Indexed i) ((,) r) s s a b -> (i -> a -> (r, b)) -> m r+l %%@= f = State.state (l %%@~ f)+{-# INLINE (%%@=) #-}++-- | Adjust the target of an 'IndexedLens' returning the intermediate result, or+-- adjust all of the targets of an 'Control.Lens.Traversal.IndexedTraversal' within the current state, and+-- return a monoidal summary of the intermediate results.+--+-- @+-- ('<%@=') :: 'MonadState' s m                 => 'IndexedLens' i s s a b      -> (i -> a -> b) -> m b+-- ('<%@=') :: ('MonadState' s m, 'Monoid' b) => 'Control.Lens.Traversal.IndexedTraversal' i s s a b -> (i -> a -> b) -> m b+-- @+(<%@=) :: MonadState s m => Over (Indexed i) ((,) b) s s a b -> (i -> a -> b) -> m b+l <%@= f = l %%@= \ i a -> let b = f i a in (b, b)+{-# INLINE (<%@=) #-}++-- | Adjust the target of an 'IndexedLens' returning the old value, or+-- adjust all of the targets of an 'Control.Lens.Traversal.IndexedTraversal' within the current state, and+-- return a monoidal summary of the old values.+--+-- @+-- ('<<%@=') :: 'MonadState' s m                 => 'IndexedLens' i s s a b      -> (i -> a -> b) -> m a+-- ('<<%@=') :: ('MonadState' s m, 'Monoid' b) => 'Control.Lens.Traversal.IndexedTraversal' i s s a b -> (i -> a -> b) -> m a+-- @+(<<%@=) :: MonadState s m => Over (Indexed i) ((,) a) s s a b -> (i -> a -> b) -> m a+l <<%@= f = State.state (l (Indexed $ \ i a -> (a, f i a)))+{-# INLINE (<<%@=) #-}++------------------------------------------------------------------------------+-- ALens Combinators+------------------------------------------------------------------------------++-- | A version of ('Control.Lens.Getter.^.') that works on 'ALens'.+--+-- >>> ("hello","world")^#_2+-- "world"+(^#) :: s -> ALens s t a b -> a+s ^# l = ipos (l sell s)+{-# INLINE (^#) #-}++-- | A version of 'Control.Lens.Setter.set' that works on 'ALens'.+--+-- >>> storing _2 "world" ("hello","there")+-- ("hello","world")+storing :: ALens s t a b -> b -> s -> t+storing l b s = ipeek b (l sell s)+{-# INLINE storing #-}++-- | A version of ('Control.Lens.Setter..~') that works on 'ALens'.+--+-- >>> ("hello","there") & _2 #~ "world"+-- ("hello","world")+(#~) :: ALens s t a b -> b -> s -> t+(#~) l b s = ipeek b (l sell s)+{-# INLINE (#~) #-}++-- | A version of ('Control.Lens.Setter.%~') that works on 'ALens'.+--+-- >>> ("hello","world") & _2 #%~ length+-- ("hello",5)+(#%~) :: ALens s t a b -> (a -> b) -> s -> t+(#%~) l f s = ipeeks f (l sell s)+{-# INLINE (#%~) #-}++-- | A version of ('%%~') that works on 'ALens'.+--+-- >>> ("hello","world") & _2 #%%~ \x -> (length x, x ++ "!")+-- (5,("hello","world!"))+(#%%~) :: Functor f => ALens s t a b -> (a -> f b) -> s -> f t+(#%%~) l f s = runPretext (l sell s) f+{-# INLINE (#%%~) #-}++-- | A version of ('Control.Lens.Setter..=') that works on 'ALens'.+(#=) :: MonadState s m => ALens s s a b -> b -> m ()+l #= f = modify (l #~ f)+{-# INLINE (#=) #-}++-- | A version of ('Control.Lens.Setter.%=') that works on 'ALens'.+(#%=) :: MonadState s m => ALens s s a b -> (a -> b) -> m ()+l #%= f = modify (l #%~ f)+{-# INLINE (#%=) #-}++-- | A version of ('<%~') that works on 'ALens'.+--+-- >>> ("hello","world") & _2 <#%~ length+-- (5,("hello",5))+(<#%~) :: ALens s t a b -> (a -> b) -> s -> (b, t)+l <#%~ f = \s -> runPretext (l sell s) $ \a -> let b = f a in (b, b)+{-# INLINE (<#%~) #-}++-- | A version of ('<%=') that works on 'ALens'.+(<#%=) :: MonadState s m => ALens s s a b -> (a -> b) -> m b+l <#%= f = l #%%= \a -> let b = f a in (b, b)+{-# INLINE (<#%=) #-}++-- | A version of ('%%=') that works on 'ALens'.+(#%%=) :: MonadState s m => ALens s s a b -> (a -> (r, b)) -> m r+l #%%= f = State.state $ \s -> runPretext (l sell s) f+{-# INLINE (#%%=) #-}++-- | A version of ('Control.Lens.Setter.<.~') that works on 'ALens'.+--+-- >>> ("hello","there") & _2 <#~ "world"+-- ("world",("hello","world"))+(<#~) :: ALens s t a b -> b -> s -> (b, t)+l <#~ b = \s -> (b, storing l b s)+{-# INLINE (<#~) #-}++-- | A version of ('Control.Lens.Setter.<.=') that works on 'ALens'.+(<#=) :: MonadState s m => ALens s s a b -> b -> m b+l <#= b = do+  l #= b+  return b+{-# INLINE (<#=) #-}++-- | There is a field for every type in the 'Void'. Very zen.+--+-- >>> [] & mapped.devoid +~ 1+-- []+--+-- >>> Nothing & mapped.devoid %~ abs+-- Nothing+--+-- @+-- 'devoid' :: 'Lens'' 'Void' a+-- @+devoid :: Over p f Void Void a b+devoid _ = absurd+{-# INLINE devoid #-}++-- | We can always retrieve a @()@ from any type.+--+-- >>> "hello"^.united+-- ()+--+-- >>> "hello" & united .~ ()+-- "hello"+united :: Lens' a ()+united f v = f () <&> \ () -> v+{-# INLINE united #-}++data First1 f a = First1 (f a) a++instance (Functor f) => Functor (First1 f) where+  fmap f (First1 fa a) = First1 (f <$> fa) (f a)+  {-# INLINE fmap #-}++instance (Functor f) => Apply (First1 f) where+  First1 ff f <.> First1 _ x = First1 (($ x) <$> ff) (f x)+  {-# INLINE (<.>) #-}++getFirst1 :: First1 f a -> f a+getFirst1 (First1 fa _) = fa+{-# INLINE getFirst1 #-}++-- | A 'Lens' focusing on the first element of a 'Traversable1' container.+--+-- >>> 2 :| [3, 4] & head1 +~ 10+-- 12 :| [3,4]+--+-- >>> Identity True ^. head1+-- True+head1 :: (Traversable1 t) => Lens' (t a) a+head1 f = getFirst1 . traverse1 (\a -> First1 (f a) a)+{-# INLINE head1 #-}++-- | A 'Lens' focusing on the last element of a 'Traversable1' container.+--+-- >>> 2 :| [3, 4] & last1 +~ 10+-- 2 :| [3,14]+--+-- >>> Node 'a' [Node 'b' [], Node 'c' []] ^. last1+-- 'c'+last1 :: (Traversable1 t) => Lens' (t a) a+last1 f = fmap getReverse . head1 f . Reverse+{-# INLINE last1 #-}++-- | Fuse a composition of lenses using 'Yoneda' to provide 'fmap' fusion.+--+-- In general, given a pair of lenses 'foo' and 'bar'+--+-- @+-- fusing (foo.bar) = foo.bar+-- @+--+-- however, @foo@ and @bar@ are either going to 'fmap' internally or they are trivial.+--+-- 'fusing' exploits the 'Yoneda' lemma to merge these separate uses into a single 'fmap'.+--+-- This is particularly effective when the choice of functor 'f' is unknown at compile+-- time or when the 'Lens' @foo.bar@ in the above description is recursive or complex+-- enough to prevent inlining.+--+-- @+-- 'fusing' :: 'Lens' s t a b -> 'Lens' s t a b+-- @+fusing :: Functor f => LensLike (Yoneda f) s t a b -> LensLike f s t a b+fusing t = \f -> lowerYoneda . t (liftYoneda . f)+{-# INLINE fusing #-}
+ src/Control/Lens/Level.hs view
@@ -0,0 +1,139 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE Trustworthy #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Level+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  Rank2Types+--+-- This module provides combinators for breadth-first searching within+-- arbitrary traversals.+----------------------------------------------------------------------------+module Control.Lens.Level+  ( Level+  , levels+  , ilevels+  ) where++import Control.Applicative+import Control.Lens.Internal.Bazaar+import Control.Lens.Internal.Context+import Control.Lens.Internal.Indexed+import Control.Lens.Internal.Level+import Control.Lens.Traversal+import Control.Lens.Type+import Data.Profunctor.Unsafe++-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import Data.Char++levelIns :: BazaarT (->) f a b t -> [Level () a]+levelIns = go 0 . (getConst #. bazaar (rmapConst (deepening ()))) where+  go k z = k `seq` runDeepening z k $ \ xs b ->+    xs : if b then (go $! k + 1) z else []+{-# INLINE levelIns #-}++levelOuts :: BazaarT (->) f a b t -> [Level j b] -> t+levelOuts bz = runFlows $ runBazaarT bz $ \ _ -> Flows $ \t -> case t of+  One _ a : _ -> a+  _           -> error "levelOuts: wrong shape"+{-# INLINE levelOuts #-}++-- | This provides a breadth-first 'Traversal' or 'Fold' of the individual+-- 'levels' of any other 'Traversal' or 'Fold' via iterative deepening+-- depth-first search. The levels are returned to you in a compressed format.+--+-- This can permit us to extract the 'levels' directly:+--+-- >>> ["hello","world"]^..levels (traverse.traverse)+-- [Zero,Zero,One () 'h',Two 0 (One () 'e') (One () 'w'),Two 0 (One () 'l') (One () 'o'),Two 0 (One () 'l') (One () 'r'),Two 0 (One () 'o') (One () 'l'),One () 'd']+--+-- But we can also traverse them in turn:+--+-- >>> ["hello","world"]^..levels (traverse.traverse).traverse+-- "hewlolrold"+--+-- We can use this to traverse to a fixed depth in the tree of ('<*>') used in the 'Traversal':+--+-- >>> ["hello","world"] & taking 4 (levels (traverse.traverse)).traverse %~ toUpper+-- ["HEllo","World"]+--+-- Or we can use it to traverse the first @n@ elements in found in that 'Traversal' regardless of the depth+-- at which they were found.+--+-- >>> ["hello","world"] & taking 4 (levels (traverse.traverse).traverse) %~ toUpper+-- ["HELlo","World"]+--+-- The resulting 'Traversal' of the 'levels' which is indexed by the depth of each 'Level'.+--+-- >>> ["dog","cat"]^@..levels (traverse.traverse) <. traverse+-- [(2,'d'),(3,'o'),(3,'c'),(4,'g'),(4,'a'),(5,'t')]+--+-- @+-- 'levels' :: 'Traversal' s t a b      -> 'IndexedTraversal' 'Int' s t ('Level' () a) ('Level' () b)+-- 'levels' :: 'Fold' s a               -> 'IndexedFold' 'Int' s ('Level' () a)+-- @+--+-- /Note:/ Internally this is implemented by using an illegal 'Applicative', as it extracts information+-- in an order that violates the 'Applicative' laws.+levels :: Applicative f+       => Traversing (->) f s t a b+       -> IndexedLensLike Int f s t (Level () a) (Level () b)+levels l f s = levelOuts bz <$> traversed f (levelIns bz) where+  bz = l sell s+{-# INLINE levels #-}++-- This is only a temporary work around added to deal with a bug in an unreleased version+-- of GHC 7.10. We should remove it as soon as we're able.+rmapConst :: Profunctor p => p a b -> p a (Const b x)+rmapConst p = Const #. p+{-# INLINE rmapConst #-}++ilevelIns :: BazaarT (Indexed i) f a b t -> [Level i a]+ilevelIns = go 0 . (getConst #. bazaar (Indexed $ \ i -> rmapConst (deepening i))) where+  go k z = k `seq` runDeepening z k $ \ xs b ->+    xs : if b then (go $! k + 1) z else []+{-# INLINE ilevelIns #-}++ilevelOuts :: BazaarT (Indexed i) f a b t -> [Level j b] -> t+ilevelOuts bz = runFlows $ runBazaarT bz $ Indexed $ \ _ _ -> Flows $ \t -> case t of+  One _ a : _ -> a+  _           -> error "ilevelOuts: wrong shape"+{-# INLINE ilevelOuts #-}++-- | This provides a breadth-first 'Traversal' or 'Fold' of the individual+-- levels of any other 'Traversal' or 'Fold' via iterative deepening depth-first+-- search. The levels are returned to you in a compressed format.+--+-- This is similar to 'levels', but retains the index of the original 'IndexedTraversal', so you can+-- access it when traversing the levels later on.+--+-- >>> ["dog","cat"]^@..ilevels (traversed<.>traversed).itraversed+-- [((0,0),'d'),((0,1),'o'),((1,0),'c'),((0,2),'g'),((1,1),'a'),((1,2),'t')]+--+-- The resulting 'Traversal' of the levels which is indexed by the depth of each 'Level'.+--+-- >>> ["dog","cat"]^@..ilevels (traversed<.>traversed)<.>itraversed+-- [((2,(0,0)),'d'),((3,(0,1)),'o'),((3,(1,0)),'c'),((4,(0,2)),'g'),((4,(1,1)),'a'),((5,(1,2)),'t')]+--+-- @+-- 'ilevels' :: 'IndexedTraversal' i s t a b      -> 'IndexedTraversal' 'Int' s t ('Level' i a) ('Level' i b)+-- 'ilevels' :: 'IndexedFold' i s a               -> 'IndexedFold' 'Int' s ('Level' i a)+-- @+--+-- /Note:/ Internally this is implemented by using an illegal 'Applicative', as it extracts information+-- in an order that violates the 'Applicative' laws.+ilevels :: Applicative f+        => Traversing (Indexed i) f s t a b+        -> IndexedLensLike Int f s t (Level i a) (Level j b)+ilevels l f s = ilevelOuts bz <$> traversed f (ilevelIns bz) where+  bz = l sell s+{-# INLINE ilevels #-}
+ src/Control/Lens/Operators.hs view
@@ -0,0 +1,168 @@+-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Operators+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-- This module exists for users who like to work with qualified imports+-- but want access to the operators from Lens.+--+-- > import qualified Control.Lens as L+-- > import Control.Lens.Operators+----------------------------------------------------------------------------+module Control.Lens.Operators+  ( -- output from scripts/operators -h+  -- * "Control.Lens.Cons"+    (<|)+  , (|>)+  , (<|~)+  , (<|=)+  , (<<|~)+  , (<<|=)+  , (<<<|~)+  , (<<<|=)+  , (|>~)+  , (|>=)+  , (<|>~)+  , (<|>=)+  , (<<|>~)+  , (<<|>=)+  -- * "Control.Lens.Fold"+  , (^..)+  , (^?)+  , (^?!)+  , (^@..)+  , (^@?)+  , (^@?!)+  -- * "Control.Lens.Getter"+  , (^.)+  , (^@.)+  -- * "Control.Lens.Indexed"+  , (<.)+  , (.>)+  , (<.>)+  -- * "Control.Lens.Lens"+  , (%%~)+  , (%%=)+  , (&)+  , (&~)+  , (<&>)+  , (??)+  , (<%~)+  , (<+~)+  , (<-~)+  , (<*~)+  , (<//~)+  , (<^~)+  , (<^^~)+  , (<**~)+  , (<||~)+  , (<&&~)+  , (<<%~)+  , (<<.~)+  , (<<?~)+  , (<<+~)+  , (<<-~)+  , (<<*~)+  , (<<//~)+  , (<<^~)+  , (<<^^~)+  , (<<**~)+  , (<<||~)+  , (<<&&~)+  , (<<<>~)+  , (<<<>:~)+  , (<%=)+  , (<+=)+  , (<-=)+  , (<*=)+  , (<//=)+  , (<^=)+  , (<^^=)+  , (<**=)+  , (<||=)+  , (<&&=)+  , (<<%=)+  , (<<.=)+  , (<<?=)+  , (<<+=)+  , (<<-=)+  , (<<*=)+  , (<<//=)+  , (<<^=)+  , (<<^^=)+  , (<<**=)+  , (<<||=)+  , (<<&&=)+  , (<<<>=)+  , (<<<>:=)+  , (<<~)+  , (<<>~)+  , (<<>=)+  , (<<>:~)+  , (<<>:=)+  , (<%@~)+  , (<<%@~)+  , (%%@~)+  , (%%@=)+  , (<%@=)+  , (<<%@=)+  , (^#)+  , (#~)+  , (#%~)+  , (#%%~)+  , (#=)+  , (#%=)+  , (<#%~)+  , (<#%=)+  , (#%%=)+  , (<#~)+  , (<#=)+  -- * "Control.Lens.Plated"+  , (...)+  -- * "Control.Lens.Review"+  , (#)+  -- * "Control.Lens.Setter"+  , (%~)+  , (.~)+  , (?~)+  , (<.~)+  , (<?~)+  , (+~)+  , (*~)+  , (-~)+  , (//~)+  , (^~)+  , (^^~)+  , (**~)+  , (||~)+  , (&&~)+  , (.=)+  , (%=)+  , (?=)+  , (+=)+  , (-=)+  , (*=)+  , (//=)+  , (^=)+  , (^^=)+  , (**=)+  , (&&=)+  , (||=)+  , (<~)+  , (<.=)+  , (<?=)+  , (<>~)+  , (<>=)+  , (<>:~)+  , (<>:=)+  , (.@~)+  , (.@=)+  , (%@~)+  , (%@=)+  ) where++import Control.Lens
src/Control/Lens/Plated.hs view
@@ -1,12 +1,22 @@+{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-}-{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE TypeOperators #-} {-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE PolyKinds #-}++#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-} -- template-haskell+#endif++#include "lens-common.h"+ ------------------------------------------------------------------------------- -- | -- Module      :  Control.Lens.Plated--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional@@ -16,15 +26,16 @@ -- used by the \"Scrap Your Boilerplate\" papers, and later inherited by Neil -- Mitchell's \"Uniplate\". ----- <http://community.haskell.org/~ndm/uniplate/>+-- <https://www.cs.york.ac.uk/fp/darcs/uniplate/uniplate.htm> -- -- The combinators in here are designed to be compatible with and subsume the--- 'uniplate' API with the notion of a 'Traversal' replacing a uniplate or--- biplate.+-- @uniplate@ API with the notion of a 'Traversal' replacing+-- a 'Data.Data.Lens.uniplate' or 'Data.Data.Lens.biplate'. ----- By implementing these combinators in terms of 'plate' instead of 'uniplate'--- additional type safety is gained, as the user is no longer responsible for--- maintaining invariants such as the number of children he received.+-- By implementing these combinators in terms of 'plate' instead of+-- 'Data.Data.Lens.uniplate' additional type safety is gained, as the user is+-- no longer responsible for maintaining invariants such as the number of+-- children they received. -- -- Note: The @Biplate@ is /deliberately/ excluded from the API here, with the -- intention that you replace them with either explicit traversals, or by using the@@ -49,20 +60,17 @@     Plated(..)    -- * Uniplate Combinators-  , children, childrenOn+  , children   , rewrite, rewriteOf, rewriteOn, rewriteOnOf   , rewriteM, rewriteMOf, rewriteMOn, rewriteMOnOf   , universe, universeOf, universeOn, universeOnOf+  , cosmos, cosmosOf, cosmosOn, cosmosOnOf   , transform, transformOf, transformOn, transformOnOf   , transformM, transformMOf, transformMOn, transformMOnOf-  , descend, descendOf, descendOn, descendOnOf-  , descendA, descendAOf, descendAOn, descendAOnOf-  , descendA_, descendAOf_, descendAOn_, descendAOnOf_-  , descendM, descendMOf, descendMOn, descendMOnOf-  , descendM_, descendMOf_, descendMOn_, descendMOnOf_   , contexts, contextsOf, contextsOn, contextsOnOf-  , holes, holesOf, holesOn, holesOnOf+  , holes, holesOn, holesOnOf   , para, paraOf+  , (...), deep    -- * Compos   -- $compos@@ -70,22 +78,43 @@    -- * Parts   , parts-  , partsOf -  -- ** Unsafe Operations-  , unsafePartsOf+  -- * Generics+  , gplate+  , gplate1+  , GPlated+  , GPlated1   )   where -import Control.Applicative+import Prelude ()++import Control.Comonad.Cofree+import qualified Control.Comonad.Trans.Cofree as CoTrans import Control.Lens.Fold import Control.Lens.Getter-import Control.Lens.Internal+import Control.Lens.Indexed+import Control.Lens.Internal.Context+import Control.Lens.Internal.Prelude+import Control.Lens.Type import Control.Lens.Setter import Control.Lens.Traversal-import Control.Lens.Type+import Control.Monad.Free as Monad+import Control.Monad.Free.Church as Church+import Control.Monad.Trans.Free as Trans+import qualified Language.Haskell.TH as TH+import Data.Data+import Data.Data.Lens import Data.Tree+import GHC.Generics +-- $setup+-- >>> :set -XDeriveGeneric -XDeriveDataTypeable+-- >>> import Control.Applicative+-- >>> import Data.Data (Data)+-- >>> import GHC.Generics (Generic)+-- >>> import Control.Lens+ -- | A 'Plated' type is one where we know how to extract its immediate self-similar children. -- -- /Example 1/:@@ -93,7 +122,7 @@ -- @ -- import Control.Applicative -- import Control.Lens--- import Control.Plated+-- import Control.Lens.Plated -- import Data.Data -- import Data.Data.Lens ('Data.Data.Lens.uniplate') -- @@@ -103,7 +132,7 @@ --   = Val 'Int' --   | Neg Expr --   | Add Expr Expr---   deriving ('Eq','Ord','Show','Read','Data','Typeable')+--   deriving ('Eq','Ord','Show','Read','Data') -- @ -- -- @@@ -125,7 +154,7 @@ -- @ -- import Control.Applicative -- import Control.Lens--- import Control.Plated+-- import Control.Lens.Plated -- import Data.Data -- import Data.Data.Lens ('Data.Data.Lens.uniplate') -- @@@ -134,7 +163,7 @@ -- data Tree a --   = Bin (Tree a) (Tree a) --   | Tip a---   deriving ('Eq','Ord','Show','Read','Data','Typeable')+--   deriving ('Eq','Ord','Show','Read','Data') -- @ -- -- @@@ -161,51 +190,98 @@ -- -- If you want to find something unplated and non-recursive with 'Data.Data.Lens.biplate' -- use the @...OnOf@ variant with 'ignored', though those usecases are much better served--- in most cases by using the existing lens combinators! e.g.+-- in most cases by using the existing 'Lens' combinators! e.g. ----- @'toListOf' 'biplate' ≡ 'universeOnOf' 'biplate' 'ignored'@.+-- @+-- 'toListOf' 'biplate' ≡ 'universeOnOf' 'biplate' 'ignored'+-- @ -- -- This same ability to explicitly pass the 'Traversal' in question is why there is no -- analogue to uniplate's @Biplate@. -- -- Moreover, since we can allow custom traversals, we implement reasonable defaults for--- polymorphic data types, that only traverse into themselves, and /not/ their+-- polymorphic data types, that only 'Control.Traversable.traverse' into themselves, and /not/ their -- polymorphic arguments.  class Plated a where   -- | 'Traversal' of the immediate children of this structure.   ---  -- The default definition finds no children.-  plate :: Simple Traversal a a-  plate = ignored+  -- If you're using GHC 7.2 or newer and your type has a 'Data' instance,+  -- 'plate' will default to 'uniplate' and you can choose to not override+  -- it with your own definition.+  plate :: Traversal' a a+  default plate :: Data a => Traversal' a a+  plate = uniplate  instance Plated [a] where   plate f (x:xs) = (x:) <$> f xs   plate _ [] = pure [] +instance Traversable f => Plated (Monad.Free f a) where+  plate f (Monad.Free as) = Monad.Free <$> traverse f as+  plate _ x         = pure x++instance (Traversable f, Traversable m) => Plated (Trans.FreeT f m a) where+  plate f (Trans.FreeT xs) = Trans.FreeT <$> traverse (traverse f) xs++instance Traversable f => Plated (Church.F f a) where+  plate f = fmap Church.toF . plate (fmap Church.fromF . f . Church.toF) . Church.fromF++-- -- This one can't work+--+-- instance (Traversable f, Traversable m) => Plated (ChurchT.FT f m a) where+--   plate f = fmap ChurchT.toFT . plate (fmap ChurchT.fromFT . f . ChurchT.toFT) . ChurchT.fromFT++instance (Traversable f, Traversable w) => Plated (CoTrans.CofreeT f w a) where+  plate f (CoTrans.CofreeT xs) = CoTrans.CofreeT <$> traverse (traverse f) xs++instance Traversable f => Plated (Cofree f a) where+  plate f (a :< as) = (:<) a <$> traverse f as+ instance Plated (Tree a) where   plate f (Node a as) = Node a <$> traverse f as +{- Default uniplate instances -}+instance Plated TH.Exp+instance Plated TH.Dec+instance Plated TH.Con+instance Plated TH.Type+instance Plated TH.Stmt+instance Plated TH.Pat+++infixr 9 ...+-- | Compose through a plate+(...) :: (Applicative f, Plated c) => LensLike f s t c c -> Over p f c c a b -> Over p f s t a b+l ... m = l . plate . m+{-# INLINE (...) #-}+++-- | Try to apply a traversal to all transitive descendants of a 'Plated' container, but+-- do not recurse through matching descendants.+--+-- @+-- 'deep' :: 'Plated' s => 'Fold' s a                 -> 'Fold' s a+-- 'deep' :: 'Plated' s => 'IndexedFold' s a          -> 'IndexedFold' s a+-- 'deep' :: 'Plated' s => 'Traversal' s s a b        -> 'Traversal' s s a b+-- 'deep' :: 'Plated' s => 'IndexedTraversal' s s a b -> 'IndexedTraversal' s s a b+-- @+deep :: (Conjoined p, Applicative f, Plated s) => Traversing p f s s a b -> Over p f s s a b+deep = deepOf plate+ ------------------------------------------------------------------------------- -- Children -------------------------------------------------------------------------------  -- | Extract the immediate descendants of a 'Plated' container. ----- @'children' ≡ 'toListOf' 'plate'@+-- @+-- 'children' ≡ 'toListOf' 'plate'+-- @ children :: Plated a => a -> [a] children = toListOf plate {-# INLINE children #-} --- | Provided for compatibility with @uniplate@.------ @'childrenOn' ≡ 'toListOf'@------ @'childrenOn' :: 'Fold' a c -> a -> [c]@-childrenOn :: Getting [c] a b c d -> a -> [c]-childrenOn = toListOf-{-# INLINE childrenOn #-}- ------------------------------------------------------------------------------- -- Rewriting -------------------------------------------------------------------------------@@ -213,11 +289,13 @@ -- | Rewrite by applying a rule everywhere you can. Ensures that the rule cannot -- be applied anywhere in the result: ----- @propRewrite r x = 'all' ('Data.Just.isNothing' . r) ('universe' ('rewrite' r x))@+-- @+-- propRewrite r x = 'all' ('Data.Just.isNothing' '.' r) ('universe' ('rewrite' r x))+-- @ -- -- Usually 'transform' is more appropriate, but 'rewrite' can give better -- compositionality. Given two single transformations @f@ and @g@, you can--- construct @\a -> f a `mplus` g a@ which performs both rewrites until a fixed point.+-- construct @\\a -> f a '<|>' g a@ which performs both rewrites until a fixed point. rewrite :: Plated a => (a -> Maybe a) -> a -> a rewrite = rewriteOf plate {-# INLINE rewrite #-}@@ -225,19 +303,21 @@ -- | Rewrite by applying a rule everywhere you can. Ensures that the rule cannot -- be applied anywhere in the result: ----- @propRewriteOf l r x = 'all' ('Data.Just.isNothing' . r) ('universeOf' l ('rewriteOf' l r x))@+-- @+-- propRewriteOf l r x = 'all' ('Data.Just.isNothing' '.' r) ('universeOf' l ('rewriteOf' l r x))+-- @ -- -- Usually 'transformOf' is more appropriate, but 'rewriteOf' can give better -- compositionality. Given two single transformations @f@ and @g@, you can--- construct @\a -> f a `mplus` g a@ which performs both rewrites until a fixed point.+-- construct @\\a -> f a '<|>' g a@ which performs both rewrites until a fixed point. -- -- @--- 'rewriteOf' :: 'Simple' 'Control.Lens.Iso.Iso' a a       -> (a -> 'Maybe' a) -> a -> a--- 'rewriteOf' :: 'Simple' 'Lens' a a      -> (a -> 'Maybe' a) -> a -> a--- 'rewriteOf' :: 'Simple' 'Traversal' a a -> (a -> 'Maybe' a) -> a -> a--- 'rewriteOf' :: 'Simple' 'Setter' a a    -> (a -> 'Maybe' a) -> a -> a+-- 'rewriteOf' :: 'Control.Lens.Iso.Iso'' a a       -> (a -> 'Maybe' a) -> a -> a+-- 'rewriteOf' :: 'Lens'' a a      -> (a -> 'Maybe' a) -> a -> a+-- 'rewriteOf' :: 'Traversal'' a a -> (a -> 'Maybe' a) -> a -> a+-- 'rewriteOf' :: 'Setter'' a a    -> (a -> 'Maybe' a) -> a -> a -- @-rewriteOf :: SimpleSetting a a -> (a -> Maybe a) -> a -> a+rewriteOf :: ASetter a b a b -> (b -> Maybe a) -> a -> b rewriteOf l f = go where   go = transformOf l (\x -> maybe x go (f x)) {-# INLINE rewriteOf #-}@@ -245,24 +325,24 @@ -- | Rewrite recursively over part of a larger structure. -- -- @--- 'rewriteOn' :: 'Plated' c => 'Simple' 'Control.Lens.Iso.Iso' a b       -> (b -> 'Maybe' b) -> a -> a--- 'rewriteOn' :: 'Plated' c => 'Simple' 'Lens' a b      -> (b -> 'Maybe' b) -> a -> a--- 'rewriteOn' :: 'Plated' c => 'Simple' 'Traversal' a b -> (b -> 'Maybe' b) -> a -> a--- 'rewriteOn' :: 'Plated' c => 'Simple' 'Setting' a b   -> (b -> 'Maybe' b) -> a -> a+-- 'rewriteOn' :: 'Plated' a => 'Control.Lens.Iso.Iso'' s a       -> (a -> 'Maybe' a) -> s -> s+-- 'rewriteOn' :: 'Plated' a => 'Lens'' s a      -> (a -> 'Maybe' a) -> s -> s+-- 'rewriteOn' :: 'Plated' a => 'Traversal'' s a -> (a -> 'Maybe' a) -> s -> s+-- 'rewriteOn' :: 'Plated' a => 'ASetter'' s a   -> (a -> 'Maybe' a) -> s -> s -- @-rewriteOn :: Plated c => Setting a b c c -> (c -> Maybe c) -> a -> b+rewriteOn :: Plated a => ASetter s t a a -> (a -> Maybe a) -> s -> t rewriteOn b = over b . rewrite {-# INLINE rewriteOn #-} --- | Rewrite recursively over part of a larger structure using a specified setter.+-- | Rewrite recursively over part of a larger structure using a specified 'Setter'. -- -- @--- 'rewriteOnOf' :: 'Plated' b => 'Simple' 'Control.Lens.Iso.Iso' a b       -> 'Simple' 'Control.Lens.Iso.Iso' b b       -> (b -> 'Maybe' b) -> a -> a--- 'rewriteOnOf' :: 'Plated' b => 'Simple' 'Lens' a b      -> 'Simple' 'Lens' b b      -> (b -> 'Maybe' b) -> a -> a--- 'rewriteOnOf' :: 'Plated' b => 'Simple' 'Traversal' a b -> 'Simple' 'Traversal' b b -> (b -> 'Maybe' b) -> a -> a--- 'rewriteOnOf' :: 'Plated' b => 'Simple' 'Setter' a b    -> 'Simple' 'Setter' b b    -> (b -> 'Maybe' b) -> a -> a+-- 'rewriteOnOf' :: 'Control.Lens.Iso.Iso'' s a       -> 'Control.Lens.Iso.Iso'' a a       -> (a -> 'Maybe' a) -> s -> s+-- 'rewriteOnOf' :: 'Lens'' s a      -> 'Lens'' a a      -> (a -> 'Maybe' a) -> s -> s+-- 'rewriteOnOf' :: 'Traversal'' s a -> 'Traversal'' a a -> (a -> 'Maybe' a) -> s -> s+-- 'rewriteOnOf' :: 'Setter'' s a    -> 'Setter'' a a    -> (a -> 'Maybe' a) -> s -> s -- @-rewriteOnOf :: Setting a b c c -> SimpleSetting c c -> (c -> Maybe c) -> a -> b+rewriteOnOf :: ASetter s t a b -> ASetter a b a b -> (b -> Maybe a) -> s -> t rewriteOnOf b l = over b . rewriteOf l {-# INLINE rewriteOnOf #-} @@ -274,20 +354,20 @@  -- | Rewrite by applying a monadic rule everywhere you recursing with a user-specified 'Traversal'. -- Ensures that the rule cannot be applied anywhere in the result.-rewriteMOf :: Monad m => SimpleLensLike (WrappedMonad m) a a -> (a -> m (Maybe a)) -> a -> m a+rewriteMOf :: Monad m => LensLike (WrappedMonad m) a b a b -> (b -> m (Maybe a)) -> a -> m b rewriteMOf l f = go where   go = transformMOf l (\x -> f x >>= maybe (return x) go) {-# INLINE rewriteMOf #-}  -- | Rewrite by applying a monadic rule everywhere inside of a structure located by a user-specified 'Traversal'. -- Ensures that the rule cannot be applied anywhere in the result.-rewriteMOn :: (Monad m, Plated c) => LensLike (WrappedMonad m) a b c c -> (c -> m (Maybe c)) -> a -> m b+rewriteMOn :: (Monad m, Plated a) => LensLike (WrappedMonad m) s t a a -> (a -> m (Maybe a)) -> s -> m t rewriteMOn b = mapMOf b . rewriteM {-# INLINE rewriteMOn #-}  -- | Rewrite by applying a monadic rule everywhere inside of a structure located by a user-specified 'Traversal', -- using a user-specified 'Traversal' for recursion. Ensures that the rule cannot be applied anywhere in the result.-rewriteMOnOf :: Monad m => LensLike (WrappedMonad m) a b c c -> SimpleLensLike (WrappedMonad m) c c -> (c -> m (Maybe c)) -> a -> m b+rewriteMOnOf :: Monad m => LensLike (WrappedMonad m) s t a b -> LensLike (WrappedMonad m) a b a b -> (b -> m (Maybe a)) -> s -> m t rewriteMOnOf b l = mapMOf b . rewriteMOf l {-# INLINE rewriteMOnOf #-} @@ -300,27 +380,71 @@ universe = universeOf plate {-# INLINE universe #-} --- | Given a fold that knows how to locate immediate children, retrieve all of the transitive descendants of a node, including itself.+-- | Given a 'Fold' that knows how to locate immediate children, retrieve all of the transitive descendants of a node, including itself. ----- @'universeOf' :: 'Fold' a a -> a -> [a]@-universeOf :: Getting [a] a b a b -> a -> [a]-universeOf l = go where-  go a = a : foldMapOf l go a+-- @+-- 'universeOf' :: 'Fold' a a -> a -> [a]+-- @+universeOf :: Getting (Endo [a]) a a -> a -> [a]+universeOf l = \x -> appEndo (universeOf' l x) [] {-# INLINE universeOf #-} +universeOf' :: Getting (Endo [a]) a a -> a -> Endo [a]+universeOf' l = go where+  go a = Endo (a :) <> foldMapOf l go a+{-# INLINE universeOf' #-}++ -- | Given a 'Fold' that knows how to find 'Plated' parts of a container retrieve them and all of their descendants, recursively.-universeOn ::  Plated c => Getting [c] a b c c -> a -> [c]+universeOn ::  Plated a => Getting (Endo [a]) s a -> s -> [a] universeOn b = universeOnOf b plate {-# INLINE universeOn #-}  -- | Given a 'Fold' that knows how to locate immediate children, retrieve all of the transitive descendants of a node, including itself that lie -- in a region indicated by another 'Fold'. ----- @'toListOf' l ≡ 'universeOnOf' l 'ignored'@-universeOnOf :: Getting [c] a b c d -> Getting [c] c d c d -> a -> [c]-universeOnOf b = foldMapOf b . universeOf+-- @+-- 'toListOf' l ≡ 'universeOnOf' l 'ignored'+-- @+universeOnOf :: Getting (Endo [a]) s a -> Getting (Endo [a]) a a -> s -> [a]+universeOnOf b = \p x -> appEndo (foldMapOf b (universeOf' p) x) [] {-# INLINE universeOnOf #-} +-- | Fold over all transitive descendants of a 'Plated' container, including itself.+cosmos :: Plated a => Fold a a+cosmos = cosmosOf plate+{-# INLINE cosmos #-}++-- | Given a 'Fold' that knows how to locate immediate children, fold all of the transitive descendants of a node, including itself.+--+-- @+-- 'cosmosOf' :: 'Fold' a a -> 'Fold' a a+-- @+cosmosOf :: (Applicative f, Contravariant f) => LensLike' f a a -> LensLike' f a a+-- The 'Contravariant' constraint isn't required for the implementation. Since any 'Traversal' produced with 'cosmosOf' is more likely than+-- not to be broken, the additional constraint serves to restrict 'cosmosOf' to 'Fold's.+cosmosOf d f s = f s *> d (cosmosOf d f) s+{-# INLINE cosmosOf #-}++-- | Given a 'Fold' that knows how to find 'Plated' parts of a container fold them and all of their descendants, recursively.+--+-- @+-- 'cosmosOn' :: 'Plated' a => 'Fold' s a -> 'Fold' s a+-- @+cosmosOn :: (Applicative f, Contravariant f, Plated a) => LensLike' f s a -> LensLike' f s a+cosmosOn d = cosmosOnOf d plate+{-# INLINE cosmosOn #-}++-- | Given a 'Fold' that knows how to locate immediate children, fold all of the transitive descendants of a node, including itself that lie+-- in a region indicated by another 'Fold'.+--+-- @+-- 'cosmosOnOf' :: 'Fold' s a -> 'Fold' a a -> 'Fold' s a+-- @+cosmosOnOf :: (Applicative f, Contravariant f) => LensLike' f s a -> LensLike' f a a -> LensLike' f s a+cosmosOnOf d p = d . cosmosOf p+{-# INLINE cosmosOnOf #-}+ ------------------------------------------------------------------------------- -- Transformation -------------------------------------------------------------------------------@@ -330,7 +454,7 @@ -- For example, replacing negative literals with literals: -- -- @--- negLits = 'transform' $ \x -> case x of+-- negLits = 'transform' $ \\x -> case x of --   Neg (Lit i) -> Lit ('negate' i) --   _           -> x -- @@@ -341,20 +465,20 @@ -- | Transform every element in the tree in a bottom-up manner over a region indicated by a 'Setter'. -- -- @--- 'transformOn' :: 'Plated' b => 'Simple' 'Traversal' a b -> (b -> b) -> a -> a--- 'transformOn' :: 'Plated' b => 'Simple' 'Setter' a b    -> (b -> b) -> a -> a+-- 'transformOn' :: 'Plated' a => 'Traversal'' s a -> (a -> a) -> s -> s+-- 'transformOn' :: 'Plated' a => 'Setter'' s a    -> (a -> a) -> s -> s -- @-transformOn :: Plated c => Setting a b c c -> (c -> c) -> a -> b+transformOn :: Plated a => ASetter s t a a -> (a -> a) -> s -> t transformOn b = over b . transform {-# INLINE transformOn #-}  -- | Transform every element by recursively applying a given 'Setter' in a bottom-up manner. -- -- @--- 'transformOf' :: 'Simple' 'Traversal' a a -> (a -> a) -> a -> a--- 'transformOf' :: 'Simple' 'Setter' a a    -> (a -> a) -> a -> a+-- 'transformOf' :: 'Traversal'' a a -> (a -> a) -> a -> a+-- 'transformOf' :: 'Setter'' a a    -> (a -> a) -> a -> a -- @-transformOf :: SimpleSetting a a -> (a -> a) -> a -> a+transformOf :: ASetter a b a b -> (b -> b) -> a -> b transformOf l f = go where   go = f . over l go {-# INLINE transformOf #-}@@ -363,10 +487,10 @@ -- in a bottom-up manner. -- -- @--- 'transformOnOf' :: 'Setter' a b -> 'Simple' 'Traversal' b b -> (b -> b) -> a -> a--- 'transformOnOf' :: 'Setter' a b -> 'Simple' 'Setter' b b    -> (b -> b) -> a -> a+-- 'transformOnOf' :: 'Setter'' s a -> 'Traversal'' a a -> (a -> a) -> s -> s+-- 'transformOnOf' :: 'Setter'' s a -> 'Setter'' a a    -> (a -> a) -> s -> s -- @-transformOnOf :: Setting a b c c -> SimpleSetting c c -> (c -> c) -> a -> b+transformOnOf :: ASetter s t a b -> ASetter a b a b -> (b -> b) -> s -> t transformOnOf b l = over b . transformOf l {-# INLINE transformOnOf #-} @@ -377,15 +501,19 @@  -- | Transform every element in the tree in a region indicated by a supplied 'Traversal', in a bottom-up manner, monadically. ----- @'transformMOn' :: ('Monad' m, 'Plated' c) => 'Simple' 'Traversal' a b -> (b -> m b) -> a -> m a@-transformMOn :: (Monad m, Plated c) => LensLike (WrappedMonad m) a b c c -> (c -> m c) -> a -> m b+-- @+-- 'transformMOn' :: ('Monad' m, 'Plated' a) => 'Traversal'' s a -> (a -> m a) -> s -> m s+-- @+transformMOn :: (Monad m, Plated a) => LensLike (WrappedMonad m) s t a a -> (a -> m a) -> s -> m t transformMOn b = mapMOf b . transformM {-# INLINE transformMOn #-}  -- | Transform every element in a tree using a user supplied 'Traversal' in a bottom-up manner with a monadic effect. ----- @'transformMOf' :: 'Monad' m => 'Simple 'Traversal' a a -> (a -> m a) -> a -> m a@-transformMOf :: Monad m => SimpleLensLike (WrappedMonad m) a a -> (a -> m a) -> a -> m a+-- @+-- 'transformMOf' :: 'Monad' m => 'Traversal'' a a -> (a -> m a) -> a -> m a+-- @+transformMOf :: Monad m => LensLike (WrappedMonad m) a b a b -> (b -> m b) -> a -> m b transformMOf l f = go where   go t = mapMOf l go t >>= f {-# INLINE transformMOf #-}@@ -393,205 +521,12 @@ -- | Transform every element in a tree that lies in a region indicated by a supplied 'Traversal', walking with a user supplied 'Traversal' in -- a bottom-up manner with a monadic effect. ----- @'transformMOnOf' :: 'Monad' m => 'Simple' 'Traversal' a b -> 'Simple' 'Traversal' b b -> (b -> m b) -> a -> m a@-transformMOnOf :: Monad m => LensLike (WrappedMonad m) a b c c -> SimpleLensLike (WrappedMonad m) c c -> (c -> m c) -> a -> m b-transformMOnOf b l = mapMOf b . transformMOf l-{-# INLINE transformMOnOf #-}------------------------------------------------------------------------------------ Descent------------------------------------------------------------------------------------ | Recurse one level into a structure. (a.k.a @composOp@ from Björn Bringert's @compos@)------ @'descend' ≡ 'over' 'plate'@-descend :: Plated a => (a -> a) -> a -> a-descend = over plate-{-# INLINE descend #-}---- | Recurse one level into a structure using a user specified recursion scheme. This is 'over', but it is supplied here--- for consistency with the uniplate API.------ @'descendOf' ≡ 'over'@--- -- @--- 'descendOf' :: 'Simple' 'Setter' a b -> (b -> b) -> a -> a--- 'descendOf' :: 'Simple' 'Traversal' a b -> (b -> b) -> a -> a--- @-descendOf :: Setting a b c d -> (c -> d) -> a -> b-descendOf = over-{-# INLINE descendOf #-}---- | Recurse one level into the parts delimited by one 'Setter', using another.------ @'descendOnOf' b l ≡ 'over' (b '.' l)@------ @--- 'descendOnOf' :: 'Simple' 'Setter' a b    -> 'Simple' 'Setter' b b    -> (b -> b) -> a -> a--- 'descendOnOf' :: 'Simple' 'Traversal' a b -> 'Simple' 'Traversal' b b -> (b -> b) -> a -> a+-- 'transformMOnOf' :: 'Monad' m => 'Traversal'' s a -> 'Traversal'' a a -> (a -> m a) -> s -> m s -- @----descendOnOf :: Setting a b c d -> Setting c d e f -> (e -> f) -> a -> b-descendOnOf b l = over (b.l)-{-# INLINE descendOnOf #-}---- | Recurse one level into the parts of the structure delimited by a 'Setter'.------ @'descendOn' b ≡ 'over' (b '.' 'plate')@------ @'descendOn' :: 'Plated' c => 'Setter' a b -> (b -> b) -> a -> a@-descendOn :: Plated c => Setting a b c c -> (c -> c) -> a -> b-descendOn b = over (b . plate)-{-# INLINE descendOn #-}------------------------------------------------------------------------------------ Applicative Descent------------------------------------------------------------------------------------ | Recurse one level into a structure with an 'Applicative' effect, this is 'plate', but it is supplied--- for consistency with the uniplate API.------ @'descendA' ≡ 'plate'@-descendA :: (Applicative f, Plated a) => (a -> f a) -> a -> f a-descendA = plate-{-# INLINE descendA #-}---- | Recurse one level into a structure using a user specified recursion scheme and 'Applicative' effects. This is 'id', but it is supplied--- for consistency with the uniplate API.------ @'descendAOf' ≡ 'id'@------ @'descendAOf' :: 'Applicative' m => 'Simple' 'Traversal' a b => (b -> m b) -> a -> m a@-descendAOf :: Applicative f => LensLike f a b c d -> (c -> f d) -> a -> f b-descendAOf = id-{-# INLINE descendAOf #-}---- | Recurse one level into the parts delimited by one 'Traversal', using another with 'Applicative' effects.------ @'descendAOnOf' ≡ ('.')@------ @'descendAOnOf' :: 'Applicative' f => 'Simple' 'Traversal' a b -> 'Simple' 'Traversal' b b -> (b -> f b) -> a -> f a@-descendAOnOf :: Applicative g => LensLike g a b c d -> LensLike g c d e f -> (e -> g f) -> a -> g b-descendAOnOf = (.)-{-# INLINE descendAOnOf #-}---- | Recurse one level into the parts of the structure delimited by a 'Traversal' with 'Applicative' effects.------ @'descendAOn' b ≡ b '.' 'plate'@------ @'descendAOn' :: ('Applicative' f, Plated' c) => 'Simple' 'Traversal' a b -> (b -> f b) -> a -> f a@-descendAOn :: (Applicative f, Plated c) => LensLike f a b c c -> (c -> f c) -> a -> f b-descendAOn b = b . plate-{-# INLINE descendAOn #-}---- |------ @'descendA_' ≡ traverseOf_' 'plate'@-descendA_ :: (Applicative f, Plated a) => (a -> f b) -> a -> f ()-descendA_ = traverseOf_ plate-{-# INLINE descendA_ #-}---- | Recurse one level into a structure using a user specified recursion scheme and 'Applicative' effects, without reconstructing the structure behind you.------ This is just 'traverseOf_', but is provided for consistency.------ @'descendAOf_' ≡ 'traverseOf_'@------ @'descendAOf_' :: 'Applicative' f => 'Fold' a b => (b -> f b) -> a -> f ()@-descendAOf_ :: Applicative f => Getting (Traversed f) a b c d -> (c -> f e) -> a -> f ()-descendAOf_ = traverseOf_-{-# INLINE descendAOf_ #-}---- | Recurse one level into the parts delimited by one 'Fold', using another with 'Applicative' effects, without reconstructing the structure behind you.------ @'descendAOnOf_' b l ≡ 'traverseOf_' (b '.' l)@------ @'descendAOnOf_' :: 'Applicative' f => 'Fold' a b -> 'Fold' b b -> (b -> f c) -> a -> f ()@-descendAOnOf_ :: Applicative f => Getting (Traversed f) a b c d -> Getting (Traversed f) c d c d -> (c -> f e) -> a -> f ()-descendAOnOf_ b l = traverseOf_ (b . l)-{-# INLINE descendAOnOf_ #-}---- | Recurse one level into the parts of the structure delimited by a 'Traversal' with monadic effects.------ @'descendAOn_' b ≡ 'traverseOf_' (b '.' 'plate')@------ @'descendAOn_' :: ('Applicative' f, 'Plated' b) => 'Simple' 'Traversal' a b -> (b -> f c) -> a -> f ()@-descendAOn_ :: (Applicative f, Plated c) => Getting (Traversed f) a b c c -> (c -> f e) -> a -> f ()-descendAOn_ b = traverseOf_ (b . plate)-{-# INLINE descendAOn_ #-}------------------------------------------------------------------------------------ Monadic Descent------------------------------------------------------------------------------------ | Recurse one level into a structure with a monadic effect. (a.k.a @composOpM@ from Björn Bringert's @compos@)------ @'descendM' ≡ 'mapMOf' 'plate'@-descendM :: (Monad m, Plated a) => (a -> m a) -> a -> m a-descendM = mapMOf plate-{-# INLINE descendM #-}---- | Recurse one level into a structure using a user specified recursion scheme and monadic effects. This is 'id', but it is--- supplied for consistency with the uniplate API.------ @'descendMOf' ≡ 'mapMOf'@------ @'descendMOf' :: 'Monad' m => 'Simple' 'Traversal' a b => (b -> m b) -> a -> m a@-descendMOf :: Monad m => LensLike (WrappedMonad m) a b c d -> (c -> m d) -> a -> m b-descendMOf = mapMOf-{-# INLINE descendMOf #-}---- | Recurse one level into the parts delimited by one 'Traversal', using another with monadic effects.------ @'descendMOnOf' b l ≡ 'mapMOf' (b '.' l)@------ @'descendMOnOf' :: 'Monad' m => 'Simple' 'Traversal' a b -> 'Simple' 'Traversal' b b -> (b -> m b) -> a -> m a@-descendMOnOf :: Monad m => LensLike (WrappedMonad m) a b c c -> SimpleLensLike (WrappedMonad m) c c -> (c -> m c) -> a -> m b-descendMOnOf b l = mapMOf (b . l)-{-# INLINE descendMOnOf #-}---- | Recurse one level into the parts of the structure delimited by a 'Traversal' with monadic effects.------ @'descendMOn' b ≡ 'mapMOf' (b . 'plate')@------ @'descendMOn' :: ('Monad' m, 'Plated' c) => 'Simple' 'Traversal' a b -> (b -> m b) -> a -> m a@-descendMOn :: (Monad m, Plated c) => LensLike (WrappedMonad m) a b c c -> (c -> m c) -> a -> m b-descendMOn b = mapMOf (b . plate)-{-# INLINE descendMOn #-}---- | Descend one level into a structure with monadic effects (a.k.a @composOpM@ from Björn Bringert's @compos@)------ @'descendM_' ≡ mapMOf_' 'plate'@-descendM_ :: (Monad m, Plated a) => (a -> m b) -> a -> m ()-descendM_ = mapMOf_ plate-{-# INLINE descendM_ #-}---- | Recurse one level into a structure using a user specified recursion scheme and monadic effects. This is just 'mapMOf_', but is provided for consistency.------ @'descendMOf_' ≡ 'mapMOf_'@------ @'descendMOf_' :: 'Monad' m => 'Fold' a b => (b -> m b) -> a -> m ()@-descendMOf_ :: Monad m => Getting (Sequenced m) a b c d -> (c -> m e) -> a -> m ()-descendMOf_ = mapMOf_-{-# INLINE descendMOf_ #-}---- | Recurse one level into the parts delimited by one 'Traversal', using another with monadic effects.------ @'descendMOnOf_' b l ≡ 'mapMOf_' (b '.' l)@------ @'descendMOnOf_' :: 'Monad' m => 'Fold' a b -> 'Fold' b b -> (b -> m b) -> a -> m ()@-descendMOnOf_ :: Monad m => Getting (Sequenced m) a b c d -> Getting (Sequenced m) c d c d -> (c -> m e) -> a -> m ()-descendMOnOf_ b l = mapMOf_ (b . l)-{-# INLINE descendMOnOf_ #-}---- | Recurse one level into the parts of the structure delimited by a 'Traversal' with monadic effects.------ @'descendMOn_' b ≡ 'mapMOf_' (b '.' 'plate')@------ @'descendMOn_' :: ('Monad' m, 'Plated' b) => 'Simple' 'Traversal' a b -> (b -> m c) -> a -> m ()@-descendMOn_ :: (Monad m, Plated c) => Getting (Sequenced m) a b c c -> (c -> m e) -> a -> m ()-descendMOn_ b = mapMOf_ (b . plate)-{-# INLINE descendMOn_ #-}+transformMOnOf :: Monad m => LensLike (WrappedMonad m) s t a b -> LensLike (WrappedMonad m) a b a b -> (b -> m b) -> s -> m t+transformMOnOf b l = mapMOf b . transformMOf l+{-# INLINE transformMOnOf #-}  ------------------------------------------------------------------------------- -- Holes and Contexts@@ -600,11 +535,13 @@ -- | Return a list of all of the editable contexts for every location in the structure, recursively. -- -- @--- propUniverse x = 'universe' x == 'map' 'pos' ('contexts' x)--- propId x = 'all' ('==' x) [extract w | w <- 'contexts' x]+-- propUniverse x = 'universe' x '==' 'map' 'Control.Comonad.Store.Class.pos' ('contexts' x)+-- propId x = 'all' ('==' x) ['Control.Lens.Internal.Context.extract' w | w <- 'contexts' x] -- @ ----- @'contexts' ≡ 'contextsOf' 'plate'@+-- @+-- 'contexts' ≡ 'contextsOf' 'plate'+-- @ contexts :: Plated a => a -> [Context a a a] contexts = contextsOf plate {-# INLINE contexts #-}@@ -612,100 +549,99 @@ -- | Return a list of all of the editable contexts for every location in the structure, recursively, using a user-specified 'Traversal' to walk each layer. -- -- @--- propUniverse l x = 'universeOf' l x == 'map' 'pos' ('contextsOf' l x)--- propId l x = 'all' ('==' x) [extract w | w <- 'contextsOf' l x]+-- propUniverse l x = 'universeOf' l x '==' 'map' 'Control.Comonad.Store.Class.pos' ('contextsOf' l x)+-- propId l x = 'all' ('==' x) ['Control.Lens.Internal.Context.extract' w | w <- 'contextsOf' l x] -- @ ----- @'contextsOf' :: 'Simple' 'Traversal' a a -> a -> ['Context' a a]@-contextsOf :: SimpleLensLike (Bazaar a a) a a -> a -> [Context a a a]-contextsOf l x = Context id x : f (holesOf l x) where+-- @+-- 'contextsOf' :: 'Traversal'' a a -> a -> ['Context' a a a]+-- @+contextsOf :: ATraversal' a a -> a -> [Context a a a]+contextsOf l x = sell x : f (map context (holesOf l x)) where   f xs = do     Context ctx child <- xs-    Context context y <- contextsOf l child-    return $ Context (ctx . context) y+    Context cont y <- contextsOf l child+    return $ Context (ctx . cont) y {-# INLINE contextsOf #-}  -- | Return a list of all of the editable contexts for every location in the structure in an areas indicated by a user supplied 'Traversal', recursively using 'plate'. ----- @'contextsOn' b ≡ 'contextsOnOf' b 'plate'@+-- @+-- 'contextsOn' b ≡ 'contextsOnOf' b 'plate'+-- @ ----- @'contextsOn' :: 'Plated' b => 'Simple' 'Traversal' a b -> a -> ['Context' b b a]@-contextsOn :: Plated c => LensLike (Bazaar c c) a b c c -> a -> [Context c c b]+-- @+-- 'contextsOn' :: 'Plated' a => 'Traversal'' s a -> s -> ['Context' a a s]+-- @+contextsOn :: Plated a => ATraversal s t a a -> s -> [Context a a t] contextsOn b = contextsOnOf b plate {-# INLINE contextsOn #-}  -- | Return a list of all of the editable contexts for every location in the structure in an areas indicated by a user supplied 'Traversal', recursively using -- another user-supplied 'Traversal' to walk each layer. ----- @'contextsOnOf' :: 'Simple' 'Traversal' a b -> 'Simple' 'Traversal' b b -> a -> ['Context' b b a]@-contextsOnOf :: LensLike (Bazaar c c) a b c c -> SimpleLensLike (Bazaar c c) c c -> a -> [Context c c b]-contextsOnOf b l = f . holesOf b where+-- @+-- 'contextsOnOf' :: 'Traversal'' s a -> 'Traversal'' a a -> s -> ['Context' a a s]+-- @+contextsOnOf :: ATraversal s t a a -> ATraversal' a a -> s -> [Context a a t]+contextsOnOf b l = f . map context . holesOf b where   f xs = do     Context ctx child <- xs-    Context context y <- contextsOf l child-    return $ Context (ctx . context) y+    Context cont y <- contextsOf l child+    return $ Context (ctx . cont) y {-# INLINE contextsOnOf #-}  -- | The one-level version of 'context'. This extracts a list of the immediate children as editable contexts. ----- Given a context you can use 'pos' to see the values, 'peek' at what the structure would be like with an edited result, or simply 'extract' the original structure.+-- Given a context you can use 'Control.Comonad.Store.Class.pos' to see the values, 'Control.Comonad.Store.Class.peek' at what the structure would be like with an edited result, or simply 'Control.Lens.Internal.Context.extract' the original structure. -- -- @--- propChildren x = 'children' l x '==' 'map' 'pos' ('holes' l x)--- propId x = 'all' ('==' x) [extract w | w <- 'holes' l x]+-- propChildren x = 'children' l x '==' 'map' 'Control.Comonad.Store.Class.pos' ('holes' l x)+-- propId x = 'all' ('==' x) ['Control.Lens.Internal.Context.extract' w | w <- 'holes' l x] -- @ ----- @'holes' = 'holesOf' 'plate'@-holes :: Plated a => a -> [Context a a a]+-- @+-- 'holes' = 'holesOf' 'plate'+-- @+holes :: Plated a => a -> [Pretext (->) a a a] holes = holesOf plate {-# INLINE holes #-} --- | The one-level version of 'contextsOf'. This extracts a list of the immediate children according to a given 'Traversal' as editable contexts.------ Given a context you can use 'pos' to see the values, 'peek' at what the structure would be like with an edited result, or simply 'extract' the original structure.+-- | An alias for 'holesOf', provided for consistency with the other combinators. -- -- @--- propChildren l x = 'childrenOf' l x '==' 'map' 'pos' ('holesOf' l x)--- propId l x = 'all' ('==' x) [extract w | w <- 'holesOf' l x]+-- 'holesOn' ≡ 'holesOf' -- @ -- -- @--- 'holesOf' :: 'Simple' 'Iso' a b       -> a -> ['Context' b a]--- 'holesOf' :: 'Simple' 'Lens' a b      -> a -> ['Context' b a]--- 'holesOf' :: 'Simple' 'Traversal' a b -> a -> ['Context' b a]--- @-holesOf :: LensLike (Bazaar c c) a b c c -> a -> [Context c c b]-holesOf l a = f (ins b) (outs b) where-  b = l sell a-  f []     _ = []-  f (x:xs) g = Context (g . (:xs)) x : f xs (g . (x:))-{-# INLINE holesOf #-}----- | An alias for 'holesOf', provided for consistency with the other combinators.------ @'holesOn' ≡ 'holesOf'@------ @--- 'holesOn' :: 'Simple' 'Iso' a b       -> a -> ['Context' b b a]--- 'holesOn' :: 'Simple' 'Lens' a b      -> a -> ['Context' b b a]--- 'holesOn' :: 'Simple' 'Traversal' a b -> a -> ['Context' b b a]+-- 'holesOn' :: 'Iso'' s a                -> s -> ['Pretext' (->) a a s]+-- 'holesOn' :: 'Lens'' s a               -> s -> ['Pretext' (->) a a s]+-- 'holesOn' :: 'Traversal'' s a          -> s -> ['Pretext' (->) a a s]+-- 'holesOn' :: 'IndexedLens'' i s a      -> s -> ['Pretext' ('Control.Lens.Internal.Indexed.Indexed' i) a a s]+-- 'holesOn' :: 'IndexedTraversal'' i s a -> s -> ['Pretext' ('Control.Lens.Internal.Indexed.Indexed' i) a a s] -- @-holesOn :: LensLike (Bazaar c c) a b c c -> a -> [Context c c b]+holesOn :: Conjoined p => Over p (Bazaar p a a) s t a a -> s -> [Pretext p a a t] holesOn = holesOf {-# INLINE holesOn #-} --- | Extract one level of holes from a container in a region specified by one 'Traversal', using another.+-- | Extract one level of 'holes' from a container in a region specified by one 'Traversal', using another. ----- @'holesOnOf' b l ≡ 'holesOf' (b '.' l)@+-- @+-- 'holesOnOf' b l ≡ 'holesOf' (b '.' l)+-- @ -- -- @--- 'holesOnOf' :: 'Simple' 'Iso' a b       -> 'Simple' 'Iso' b b       -> a -> ['Context' b a]--- 'holesOnOf' :: 'Simple' 'Lens' a b      -> 'Simple' 'Lens' b b      -> a -> ['Context' b a]--- 'holesOnOf' :: 'Simple' 'Traversal' a b -> 'Simple' 'Traversal' b b -> a -> ['Context' b a]+-- 'holesOnOf' :: 'Iso'' s a       -> 'Iso'' a a                -> s -> ['Pretext' (->) a a s]+-- 'holesOnOf' :: 'Lens'' s a      -> 'Lens'' a a               -> s -> ['Pretext' (->) a a s]+-- 'holesOnOf' :: 'Traversal'' s a -> 'Traversal'' a a          -> s -> ['Pretext' (->) a a s]+-- 'holesOnOf' :: 'Lens'' s a      -> 'IndexedLens'' i a a      -> s -> ['Pretext' ('Control.Lens.Internal.Indexed.Indexed' i) a a s]+-- 'holesOnOf' :: 'Traversal'' s a -> 'IndexedTraversal'' i a a -> s -> ['Pretext' ('Control.Lens.Internal.Indexed.Indexed' i) a a s] -- @-holesOnOf :: LensLike (Bazaar e e) a b c d -> LensLike (Bazaar e e) c d e e -> a -> [Context e e b]-holesOnOf b l = holesOf (b.l)+holesOnOf :: Conjoined p+          => LensLike (Bazaar p  r r) s t a b+          -> Over p (Bazaar p r r) a b r r+          -> s -> [Pretext p r r t]+holesOnOf b l = holesOf (b . l) {-# INLINE holesOnOf #-}  -------------------------------------------------------------------------------@@ -714,15 +650,19 @@  -- | Perform a fold-like computation on each value, technically a paramorphism. ----- @'paraOf' :: 'Fold' a a -> (a -> [r] -> r) -> a -> r@-paraOf :: Getting [a] a b a b -> (a -> [r] -> r) -> a -> r+-- @+-- 'paraOf' :: 'Fold' a a -> (a -> [r] -> r) -> a -> r+-- @+paraOf :: Getting (Endo [a]) a a -> (a -> [r] -> r) -> a -> r paraOf l f = go where   go a = f a (go <$> toListOf l a) {-# INLINE paraOf #-}  -- | Perform a fold-like computation on each value, technically a paramorphism. ----- @'para' ≡ 'paraOf' 'plate'@+-- @+-- 'para' ≡ 'paraOf' 'plate'+-- @ para :: Plated a => (a -> [r] -> r) -> a -> r para = paraOf plate {-# INLINE para #-}@@ -740,7 +680,7 @@ -- -- @ -- 'composOpMonoid' ≡ 'foldMapOf' 'plate'--- 'composOpMPlus' f ≡ 'msumOf' ('plate' '.' 'to' f)+-- 'composOpMPlus' f ≡ 'msumOf' ('plate' '.' 'Control.Lens.Getter.to' f) -- 'composOp' ≡ 'descend' ≡ 'over' 'plate' -- 'composOpM' ≡ 'descendM' ≡ 'mapMOf' 'plate' -- 'composOpM_' ≡ 'descendM_' ≡ 'mapMOf_' 'plate'@@ -748,7 +688,9 @@  -- | Fold the immediate children of a 'Plated' container. ----- @'composOpFold' z c f = 'foldrOf' 'plate' (c '.' f) z@+-- @+-- 'composOpFold' z c f = 'foldrOf' 'plate' (c '.' f) z+-- @ composOpFold :: Plated a => b -> (b -> b -> b) -> (a -> b) -> a -> b composOpFold z c f = foldrOf plate (c . f) z {-# INLINE composOpFold #-}@@ -759,82 +701,156 @@  -- | The original @uniplate@ combinator, implemented in terms of 'Plated' as a 'Lens'. ----- @'parts' ≡ 'partsOf' 'plate'@+-- @+-- 'parts' ≡ 'partsOf' 'plate'+-- @ ----- The resulting lens is safer to use as it ignores 'over-application' and deals gracefully with under-application,--- but it is only a proper lens if you don't change the list 'length'!-parts :: Plated a => Simple Lens a [a]+-- The resulting 'Lens' is safer to use as it ignores 'over-application' and deals gracefully with under-application,+-- but it is only a proper 'Lens' if you don't change the list 'length'!+parts :: Plated a => Lens' a [a] parts = partsOf plate {-# INLINE parts #-} --- | 'partsOf' turns a 'Traversal' into a lens that resembles an early version of the @uniplate@ (or @biplate@) type.+-------------------------------------------------------------------------------+-- Generics+-------------------------------------------------------------------------------++-- | Implement 'plate' operation for a type using its 'Generic' instance. ----- /Note:/ You should really try to maintain the invariant of the number of children in the list.+-- Note: the behavior may be different than with 'uniplate' in some special cases.+-- 'gplate' doesn't look through other types in a group of mutually+-- recursive types. ----- Any extras will be lost. If you do not supply enough, then the remainder will come from the original structure.+-- For example consider mutually recursive even and odd natural numbers: ----- So technically, this is only a lens if you do not change the number of results it returns.+-- >>> data Even = Z | E Odd deriving (Show, Generic, Data); data Odd = O Even deriving (Show, Generic, Data) ----- @--- 'partsOf' :: 'Simple' 'Control.Lens.Iso.Iso' a b       -> 'Simple' 'Lens' a [b]--- 'partsOf' :: 'Simple' 'Lens' a b      -> 'Simple' 'Lens' a [b]--- 'partsOf' :: 'Simple' 'Traversal' a b -> 'Simple' 'Lens' a [b]--- @-partsOf :: LensLike (Bazaar c c) a b c c -> Lens a b [c] [c]-partsOf l f a = outs b <$> f (ins b) where b = l sell a-{-# INLINE partsOf #-}---- | 'unsafePartsOf' turns a 'Traversal' into a @uniplate@ (or @biplate@) family.+-- Then 'uniplate', which is based on `Data`, finds+-- all even numbers less or equal than four: ----- If you do not need the types of @c@ and @d@ to be different, it is recommended that--- you use 'partsOf'+-- >>> import Data.Data.Lens (uniplate)+-- >>> universeOf uniplate (E (O (E (O Z))))+-- [E (O (E (O Z))),E (O Z),Z] ----- It is generally safer to traverse with the 'Bazaar' rather than use this--- combinator. However, it is sometimes convenient.+-- but 'gplate' doesn't see through @Odd@. ----- This is unsafe because if you don't supply at least as many @d@'s as you were--- given @c@'s, then the reconstruction of @b@ /will/ result in an error!+-- >>> universeOf gplate (E (O (E (O Z))))+-- [E (O (E (O Z)))] ----- @--- 'unsafePartsOf' :: 'Control.Lens.Iso.Iso' a b c d       -> 'Lens' a b [c] [d]--- 'unsafePartsOf' :: 'Lens' a b c d      -> 'Lens' a b [c] [d]--- 'unsafePartsOf' :: 'Traversal' a b c d -> 'Lens' a b [c] [d]--- @-unsafePartsOf :: LensLike (Bazaar c d) a b c d -> Lens a b [c] [d]-unsafePartsOf l f a = unsafeOuts b <$> f (ins b) where b = l sell a-{-# INLINE unsafePartsOf #-}+-- If using 'Data' is not an option, you can still write the traversal manually.+-- It is sometimes useful to use helper traversals+--+-- >>> :{+-- let oddeven :: Traversal' Odd Even+--     oddeven f (O n) = O <$> f n+--     evenplate :: Traversal' Even Even+--     evenplate f Z     = pure Z+--     evenplate f (E n) = E <$> oddeven f n+-- :}+--+-- >>> universeOf evenplate (E (O (E (O Z))))+-- [E (O (E (O Z))),E (O Z),Z]+--+gplate :: (Generic a, GPlated a (Rep a)) => Traversal' a a+gplate f x = GHC.Generics.to <$> gplate' f (GHC.Generics.from x)+{-# INLINE gplate #-} ----------------------------------------------------------------------------------- Misc.--------------------------------------------------------------------------------+class GPlated a g where+  gplate' :: Traversal' (g p) a -ins :: Bazaar c d a -> [c]-ins (Bazaar m) = getConst (m (Const . return))-{-# INLINE ins #-}+instance GPlated a f => GPlated a (M1 i c f) where+  gplate' f (M1 x) = M1 <$> gplate' f x+  {-# INLINE gplate' #-} -newtype Out c a = Out { withOut :: [c] -> (a, [c]) }+instance (GPlated a f, GPlated a g) => GPlated a (f :+: g) where+  gplate' f (L1 x) = L1 <$> gplate' f x+  gplate' f (R1 x) = R1 <$> gplate' f x+  {-# INLINE gplate' #-} -instance Functor (Out c) where-  fmap f (Out m) = Out $ \cs -> case m cs of-    (as, ds) -> (f as, ds)-  {-# INLINE fmap #-}+instance (GPlated a f, GPlated a g) => GPlated a (f :*: g) where+  gplate' f (x :*: y) = (:*:) <$> gplate' f x <*> gplate' f y+  {-# INLINE gplate' #-} -instance Applicative (Out c) where-  pure a = Out $ \cs -> (a, cs)-  {-# INLINE pure #-}-  Out mf <*> Out ma = Out $ \cs -> case mf cs of-    (f,  ds) -> case ma ds of-       (a,  es) -> (f a, es)-  {-# INLINE (<*>) #-}+instance {-# OVERLAPPING #-} GPlated a (K1 i a) where+  gplate' f (K1 x) = K1 <$> f x+  {-# INLINE gplate' #-} -outs :: Bazaar c c a -> [c] -> a-outs (Bazaar m) = fst . withOut (m $ \c -> Out $ \cs -> case cs of-  [] -> (c, [])-  (d:ds) -> (d, ds))-{-# INLINE outs #-}+instance GPlated a (K1 i b) where+  gplate' _ = pure+  {-# INLINE gplate' #-} -unsafeOuts :: Bazaar c d a -> [d] -> a-unsafeOuts (Bazaar m) = fst . withOut (m $ \_ -> Out $ \cs -> case cs of-  (d:ds) -> (d, ds)-  [] -> error "unsafePartsOf: not enough elements were supplied")-{-# INLINE unsafeOuts #-}+instance GPlated a U1 where+  gplate' _ = pure+  {-# INLINE gplate' #-}++instance GPlated a V1 where+  gplate' _ v = v `seq` error "GPlated/V1"+  {-# INLINE gplate' #-}++instance GPlated a (URec b) where+  gplate' _ = pure+  {-# INLINE gplate' #-}++-- | Implement 'plate' operation for a type using its 'Generic1' instance.+gplate1 :: (Generic1 f, GPlated1 f (Rep1 f)) => Traversal' (f a) (f a)+gplate1 f x = GHC.Generics.to1 <$> gplate1' f (GHC.Generics.from1 x)+{-# INLINE gplate1 #-}++class GPlated1 f g where+  gplate1' :: Traversal' (g a) (f a)++-- | recursive match+instance GPlated1 f g => GPlated1 f (M1 i c g) where+  gplate1' f (M1 x) = M1 <$> gplate1' f x+  {-# INLINE gplate1' #-}++-- | recursive match+instance (GPlated1 f g, GPlated1 f h) => GPlated1 f (g :+: h) where+  gplate1' f (L1 x) = L1 <$> gplate1' f x+  gplate1' f (R1 x) = R1 <$> gplate1' f x+  {-# INLINE gplate1' #-}++-- | recursive match+instance (GPlated1 f g, GPlated1 f h) => GPlated1 f (g :*: h) where+  gplate1' f (x :*: y) = (:*:) <$> gplate1' f x <*> gplate1' f y+  {-# INLINE gplate1' #-}++-- | ignored+instance GPlated1 f (K1 i a) where+  gplate1' _ = pure+  {-# INLINE gplate1' #-}++-- | ignored+instance GPlated1 f Par1 where+  gplate1' _ = pure+  {-# INLINE gplate1' #-}++-- | ignored+instance GPlated1 f U1 where+  gplate1' _ = pure+  {-# INLINE gplate1' #-}++-- | ignored+instance GPlated1 f V1 where+  gplate1' _ = pure+  {-# INLINE gplate1' #-}++-- | match+instance {-# OVERLAPPING #-} GPlated1 f (Rec1 f) where+  gplate1' f (Rec1 x) = Rec1 <$> f x+  {-# INLINE gplate1' #-}++-- | ignored+instance GPlated1 f (Rec1 g) where+  gplate1' _ = pure+  {-# INLINE gplate1' #-}++-- | recursive match under outer 'Traversable' instance+instance (Traversable t, GPlated1 f g) => GPlated1 f (t :.: g) where+  gplate1' f (Comp1 x) = Comp1 <$> traverse (gplate1' f) x+  {-# INLINE gplate1' #-}++-- | ignored+instance GPlated1 f (URec a) where+  gplate1' _ = pure+  {-# INLINE gplate1' #-}
+ src/Control/Lens/Prism.hs view
@@ -0,0 +1,454 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Rank2Types #-}++#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-}+#endif++#include "lens-common.h"++-------------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Prism+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  non-portable+--+-------------------------------------------------------------------------------+module Control.Lens.Prism+  (+  -- * Prisms+    Prism, Prism'+  , APrism, APrism'+  -- * Constructing Prisms+  , prism+  , prism'+  -- * Consuming Prisms+  , withPrism+  , clonePrism+  , outside+  , aside+  , without+  , below+  , isn't+  , matching+  , matching'+  -- * Common Prisms+  , _Left+  , _Right+  , _Just+  , _Nothing+  , _Void+  , _Show+  , only+  , nearly+  , Prefixed(..)+  , Suffixed(..)+  -- * Prismatic profunctors+  , Choice(..)+  ) where++import Prelude ()++import Control.Applicative+import qualified Control.Lens.Internal.List as List+import Control.Lens.Internal.Prism+import Control.Lens.Internal.Prelude+import Control.Lens.Lens+import Control.Lens.Review+import Control.Lens.Type+import Control.Monad+import qualified Data.ByteString as BS+import qualified Data.ByteString.Lazy as BL+import qualified Data.List as List+import Data.Profunctor.Rep+import qualified Data.Text as TS+import qualified Data.Text.Lazy as TL++-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import Numeric.Natural+-- >>> import Debug.SimpleReflect.Expr+-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g)+-- >>> let isLeft  (Left  _) = True; isLeft  _ = False+-- >>> let isRight (Right _) = True; isRight _ = False+-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f+-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g++------------------------------------------------------------------------------+-- Prism Internals+------------------------------------------------------------------------------++-- | If you see this in a signature for a function, the function is expecting a 'Prism'.+type APrism s t a b = Market a b a (Identity b) -> Market a b s (Identity t)++-- | @+-- type APrism' = 'Simple' 'APrism'+-- @+type APrism' s a = APrism s s a a++-- | Convert 'APrism' to the pair of functions that characterize it.+withPrism :: APrism s t a b -> ((b -> t) -> (s -> Either t a) -> r) -> r+withPrism k f = case coerce (k (Market Identity Right)) of+  Market bt seta -> f bt seta+{-# INLINE withPrism #-}++-- | Clone a 'Prism' so that you can reuse the same monomorphically typed 'Prism' for different purposes.+--+-- See 'Control.Lens.Lens.cloneLens' and 'Control.Lens.Traversal.cloneTraversal' for examples of why you might want to do this.+clonePrism :: APrism s t a b -> Prism s t a b+clonePrism k = withPrism k $ \bt sta -> prism bt sta+{-# INLINE clonePrism #-}++------------------------------------------------------------------------------+-- Prism Combinators+------------------------------------------------------------------------------++-- | Build a 'Control.Lens.Prism.Prism'.+--+-- @'Either' t a@ is used instead of @'Maybe' a@ to permit the types of @s@ and @t@ to differ.+--+prism :: (b -> t) -> (s -> Either t a) -> Prism s t a b+prism bt seta = dimap seta (either pure (fmap bt)) . right'+{-# INLINE prism #-}++-- | This is usually used to build a 'Prism'', when you have to use an operation like+-- 'Data.Typeable.cast' which already returns a 'Maybe'.+prism' :: (b -> s) -> (s -> Maybe a) -> Prism s s a b+prism' bs sma = prism bs (\s -> maybe (Left s) Right (sma s))+{-# INLINE prism' #-}++-- | Use a 'Prism' as a kind of first-class pattern.+--+-- @'outside' :: 'Prism' s t a b -> 'Lens' (t -> r) (s -> r) (b -> r) (a -> r)@++-- TODO: can we make this work with merely Strong?+outside :: Representable p => APrism s t a b -> Lens (p t r) (p s r) (p b r) (p a r)+outside k = withPrism k $ \bt seta f ft ->+  f (lmap bt ft) <&> \fa -> tabulate $ either (sieve ft) (sieve fa) . seta+{-# INLINE outside #-}++-- | Given a pair of prisms, project sums.+--+-- Viewing a 'Prism' as a co-'Lens', this combinator can be seen to be dual to 'Control.Lens.Lens.alongside'.+without :: APrism s t a b+        -> APrism u v c d+        -> Prism (Either s u) (Either t v) (Either a c) (Either b d)+without k k' =+  withPrism k         $ \bt seta ->+  withPrism k'        $ \dv uevc ->+  prism (bimap bt dv) $ \su ->+  case su of+    Left s  -> bimap Left Left (seta s)+    Right u -> bimap Right Right (uevc u)+{-# INLINE without #-}++-- | Use a 'Prism' to work over part of a structure.+--+aside :: APrism s t a b -> Prism (e, s) (e, t) (e, a) (e, b)+aside k =+  withPrism k     $ \bt seta ->+  prism (fmap bt) $ \(e,s) ->+  case seta s of+    Left t  -> Left  (e,t)+    Right a -> Right (e,a)+{-# INLINE aside #-}++-- | 'lift' a 'Prism' through a 'Traversable' functor, giving a Prism that matches only if all the elements of the container match the 'Prism'.+--+-- >>> [Left 1, Right "foo", Left 4, Right "woot"]^..below _Right+-- []+--+-- >>> [Right "hail hydra!", Right "foo", Right "blah", Right "woot"]^..below _Right+-- [["hail hydra!","foo","blah","woot"]]+below :: Traversable f => APrism' s a -> Prism' (f s) (f a)+below k =+  withPrism k     $ \bt seta ->+  prism (fmap bt) $ \s ->+  case traverse seta s of+    Left _  -> Left s+    Right t -> Right t+{-# INLINE below #-}++-- | Check to see if this 'Prism' doesn't match.+--+-- >>> isn't _Left (Right 12)+-- True+--+-- >>> isn't _Left (Left 12)+-- False+--+-- >>> isn't _Empty []+-- False+--+-- @+-- 'isn't' = 'not' . 'Control.Lens.Extra.is'+-- 'isn't' = 'hasn't'+-- @+isn't :: APrism s t a b -> s -> Bool+isn't k s =+  case matching k s of+    Left  _ -> True+    Right _ -> False+{-# INLINE isn't #-}++-- | Retrieve the value targeted by a 'Prism' or return the+-- original value while allowing the type to change if it does+-- not match.+--+-- >>> matching _Just (Just 12)+-- Right 12+--+-- >>> matching _Just (Nothing :: Maybe Int) :: Either (Maybe Bool) Int+-- Left Nothing+matching :: APrism s t a b -> s -> Either t a+matching k = withPrism k $ \_ seta -> seta+{-# INLINE matching #-}++-- | Like 'matching', but also works for combinations of 'Lens' and 'Prism's,+-- and also 'Traversal's.+--+-- >>> matching' (_2 . _Just) ('x', Just True)+-- Right True+--+-- >>> matching' (_2 . _Just) ('x', Nothing :: Maybe Int) :: Either (Char, Maybe Bool) Int+-- Left ('x',Nothing)+--+-- >>> matching' traverse "" :: Either [Int] Char+-- Left []+--+-- >>> matching' traverse "xyz" :: Either [Int] Char+-- Right 'x'+matching' :: LensLike (Either a) s t a b -> s -> Either t a+matching' k = either Right Left . k Left+{-# INLINE matching' #-}++------------------------------------------------------------------------------+-- Common Prisms+------------------------------------------------------------------------------++-- | This 'Prism' provides a 'Traversal' for tweaking the 'Left' half of an 'Either':+--+-- >>> over _Left (+1) (Left 2)+-- Left 3+--+-- >>> over _Left (+1) (Right 2)+-- Right 2+--+-- >>> Right 42 ^._Left :: String+-- ""+--+-- >>> Left "hello" ^._Left+-- "hello"+--+-- It also can be turned around to obtain the embedding into the 'Left' half of an 'Either':+--+-- >>> _Left # 5+-- Left 5+--+-- >>> 5^.re _Left+-- Left 5+_Left :: Prism (Either a c) (Either b c) a b+_Left = prism Left $ either Right (Left . Right)+{-# INLINE _Left #-}++-- | This 'Prism' provides a 'Traversal' for tweaking the 'Right' half of an 'Either':+--+-- >>> over _Right (+1) (Left 2)+-- Left 2+--+-- >>> over _Right (+1) (Right 2)+-- Right 3+--+-- >>> Right "hello" ^._Right+-- "hello"+--+-- >>> Left "hello" ^._Right :: [Double]+-- []+--+-- It also can be turned around to obtain the embedding into the 'Right' half of an 'Either':+--+-- >>> _Right # 5+-- Right 5+--+-- >>> 5^.re _Right+-- Right 5+_Right :: Prism (Either c a) (Either c b) a b+_Right = prism Right $ either (Left . Left) Right+{-# INLINE _Right #-}++-- | This 'Prism' provides a 'Traversal' for tweaking the target of the value of 'Just' in a 'Maybe'.+--+-- >>> over _Just (+1) (Just 2)+-- Just 3+--+-- Unlike 'Data.Traversable.traverse' this is a 'Prism', and so you can use it to inject as well:+--+-- >>> _Just # 5+-- Just 5+--+-- >>> 5^.re _Just+-- Just 5+--+-- Interestingly,+--+-- @+-- m '^?' '_Just' ≡ m+-- @+--+-- >>> Just x ^? _Just+-- Just x+--+-- >>> Nothing ^? _Just+-- Nothing+_Just :: Prism (Maybe a) (Maybe b) a b+_Just = prism Just $ maybe (Left Nothing) Right+{-# INLINE _Just #-}++-- | This 'Prism' provides the 'Traversal' of a 'Nothing' in a 'Maybe'.+--+-- >>> Nothing ^? _Nothing+-- Just ()+--+-- >>> Just () ^? _Nothing+-- Nothing+--+-- But you can turn it around and use it to construct 'Nothing' as well:+--+-- >>> _Nothing # ()+-- Nothing+_Nothing :: Prism' (Maybe a) ()+_Nothing = prism' (const Nothing) $ maybe (Just ()) (const Nothing)+{-# INLINE _Nothing #-}++-- | 'Void' is a logically uninhabited data type.+--+-- This is a 'Prism' that will always fail to match.+_Void :: Prism s s a Void+_Void = prism absurd Left+{-# INLINE _Void #-}++-- | This 'Prism' compares for exact equality with a given value.+--+-- >>> only 4 # ()+-- 4+--+-- >>> 5 ^? only 4+-- Nothing+only :: Eq a => a -> Prism' a ()+only a = prism' (\() -> a) $ guard . (a ==)+{-# INLINE only #-}+++-- | This 'Prism' compares for approximate equality with a given value and a predicate for testing,+-- an example where the value is the empty list and the predicate checks that a list is empty (same+-- as 'Control.Lens.Empty._Empty' with the 'Control.Lens.Empty.AsEmpty' list instance):+--+-- >>> nearly [] null # ()+-- []+-- >>> [1,2,3,4] ^? nearly [] null+-- Nothing+--+-- @'nearly' [] 'Prelude.null' :: 'Prism'' [a] ()@+--+-- To comply with the 'Prism' laws the arguments you supply to @nearly a p@ are somewhat constrained.+--+-- We assume @p x@ holds iff @x ≡ a@. Under that assumption then this is a valid 'Prism'.+--+-- This is useful when working with a type where you can test equality for only a subset of its+-- values, and the prism selects such a value.++nearly :: a -> (a -> Bool) -> Prism' a ()+nearly a p = prism' (\() -> a) $ guard . p+{-# INLINE nearly #-}++-- | This is an improper prism for text formatting based on 'Read' and 'Show'.+--+-- This 'Prism' is \"improper\" in the sense that it normalizes the text formatting, but round tripping+-- is idempotent given sane 'Read'/'Show' instances.+--+-- >>> _Show # 2+-- "2"+--+-- >>> "EQ" ^? _Show :: Maybe Ordering+-- Just EQ+--+-- @+-- '_Show' ≡ 'prism'' 'show' 'readMaybe'+-- @+_Show :: (Read a, Show a) => Prism' String a+_Show = prism show $ \s -> case reads s of+  [(a,"")] -> Right a+  _ -> Left s+{-# INLINE _Show #-}++class Prefixed t where+  -- | A 'Prism' stripping a prefix from a sequence when used as a 'Traversal',+  -- or prepending that prefix when run backwards:+  --+  -- >>> "preview" ^? prefixed "pre"+  -- Just "view"+  --+  -- >>> "review" ^? prefixed "pre"+  -- Nothing+  --+  -- >>> prefixed "pre" # "amble"+  -- "preamble"+  prefixed :: t -> Prism' t t++instance Eq a => Prefixed [a] where+  prefixed ps = prism' (ps ++) (List.stripPrefix ps)+  {-# INLINE prefixed #-}++instance Prefixed TS.Text where+  prefixed p = prism' (p <>) (TS.stripPrefix p)+  {-# INLINE prefixed #-}++instance Prefixed TL.Text where+  prefixed p = prism' (p <>) (TL.stripPrefix p)+  {-# INLINE prefixed #-}++instance Prefixed BS.ByteString where+  prefixed p = prism' (p <>) (BS.stripPrefix p)+  {-# INLINE prefixed #-}++instance Prefixed BL.ByteString where+  prefixed p = prism' (p <>) (BL.stripPrefix p)+  {-# INLINE prefixed #-}++class Suffixed t where+  -- | A 'Prism' stripping a suffix from a sequence when used as a 'Traversal',+  -- or appending that suffix when run backwards:+  --+  -- >>> "review" ^? suffixed "view"+  -- Just "re"+  --+  -- >>> "review" ^? suffixed "tire"+  -- Nothing+  --+  -- >>> suffixed ".o" # "hello"+  -- "hello.o"+  suffixed :: t -> Prism' t t++instance Eq a => Suffixed [a] where+  suffixed qs = prism' (++ qs) (List.stripSuffix qs)+  {-# INLINE suffixed #-}++instance Suffixed TS.Text where+  suffixed qs = prism' (<> qs) (TS.stripSuffix qs)+  {-# INLINE suffixed #-}++instance Suffixed TL.Text where+  suffixed qs = prism' (<> qs) (TL.stripSuffix qs)+  {-# INLINE suffixed #-}++instance Suffixed BS.ByteString where+  suffixed qs = prism' (<> qs) (BS.stripSuffix qs)+  {-# INLINE suffixed #-}++instance Suffixed BL.ByteString where+  suffixed qs = prism' (<> qs) (BL.stripSuffix qs)+  {-# INLINE suffixed #-}
+ src/Control/Lens/Profunctor.hs view
@@ -0,0 +1,135 @@+{-# LANGUAGE CPP #-}+-------------------------------------------------------------------------------+-- | This module provides conversion functions between the optics defined in+-- this library and 'Profunctor'-based optics.+--+-- The goal of these functions is to provide an interoperability layer between+-- the two styles of optics, and not to reimplement all the library in terms of+-- 'Profunctor' optics.++module Control.Lens.Profunctor+  ( -- * Profunctor optic+    OpticP++    -- * Conversion from Van Laarhoven optics+  , fromLens+  , fromIso+  , fromPrism+  , fromSetter+  , fromTraversal++    -- * Conversion to Van Laarhoven optics+  , toLens+  , toIso+  , toPrism+  , toSetter+  , toTraversal+  ) where++import Prelude ()++import Control.Lens.Internal.Prelude+import Control.Lens.Type (Optic, LensLike)+import Control.Lens.Internal.Context (Context (..), sell)+import Control.Lens.Internal.Profunctor (WrappedPafb (..))+import Control.Lens (ASetter, ATraversal, cloneTraversal, Settable)+import Data.Profunctor (Star (..))+import Data.Profunctor.Mapping (Mapping (..))+import Data.Profunctor.Traversing (Traversing (..))++-- | Profunctor optic.+type OpticP p s t a b = p a b -> p s t++--------------------------------------------------------------------------------+-- Conversion from Van Laarhoven optics+--------------------------------------------------------------------------------++-- | Converts a 'Control.Lens.Type.Lens' to a 'Profunctor'-based one.+--+-- @+-- 'fromLens' :: 'Control.Lens.Type.Lens' s t a b -> LensP s t a b+-- @+fromLens :: Strong p => LensLike (Context a b) s t a b -> OpticP p s t a b+fromLens l p =+  dimap+    (\s -> let Context f a = l sell s in (f, a))+    (uncurry id)+    (second' p)++-- | Converts a 'Control.Lens.Type.Iso' to a 'Profunctor'-based one.+--+-- @+-- 'fromIso' :: 'Control.Lens.Type.Iso' s t a b -> IsoP s t a b+-- @+fromIso :: Profunctor p => Optic p Identity s t a b -> OpticP p s t a b+fromIso p pab = rmap runIdentity (p (rmap Identity pab))++-- | Converts a 'Control.Lens.Type.Prism' to a 'Profunctor'-based one.+--+-- @+-- 'fromPrism' :: 'Control.Lens.Type.Prism' s t a b -> PrismP s t a b+-- @+fromPrism :: Choice p => Optic p Identity s t a b -> OpticP p s t a b+fromPrism p pab = rmap runIdentity (p (rmap Identity pab))++-- | Converts a 'Control.Lens.Type.Setter' to a 'Profunctor'-based one.+--+-- @+-- 'fromSetter' :: 'Control.Lens.Type.Setter' s t a b -> SetterP s t a b+-- @+fromSetter :: Mapping p => ASetter s t a b -> OpticP p s t a b+fromSetter s = roam s'+  where+    s' f = runIdentity . s (Identity . f)++-- | Converts a 'Control.Lens.Type.Traversal' to a 'Profunctor'-based one.+--+-- @+-- 'fromTraversal' :: 'Control.Lens.Type.Traversal' s t a b -> TraversalP s t a b+-- @+fromTraversal :: Traversing p => ATraversal s t a b -> OpticP p s t a b+fromTraversal l = wander (cloneTraversal l)++--------------------------------------------------------------------------------+-- Conversion to Van Laarhoven optics+--------------------------------------------------------------------------------++-- | Obtain a 'Control.Lens.Type.Prism' from a 'Profunctor'-based one.+--+-- @+-- 'toPrism' :: PrismP s t a b -> 'Control.Lens.Type.Prism' s t a b+-- @+toPrism :: (Choice p, Applicative f) => OpticP (WrappedPafb f p) s t a b -> Optic p f s t a b+toPrism p = unwrapPafb . p . WrapPafb++-- | Obtain a 'Control.Lens.Type.Iso' from a 'Profunctor'-based one.+--+-- @+-- 'toIso' :: IsoP s t a b -> 'Control.Lens.Type.Iso' s t a b+-- @+toIso :: (Profunctor p, Functor f) => OpticP (WrappedPafb f p) s t a b -> Optic p f s t a b+toIso p = unwrapPafb . p . WrapPafb++-- | Obtain a 'Control.Lens.Type.Lens' from a 'Profunctor'-based one.+--+-- @+-- 'toLens' :: LensP s t a b -> 'Control.Lens.Type.Lens' s t a b+-- @+toLens :: Functor f => OpticP (Star f) s t a b -> LensLike f s t a b+toLens p = runStar . p . Star++-- | Obtain a 'Control.Lens.Type.Setter' from a 'Profunctor'-based one.+--+-- @+-- 'toSetter' :: SetterP s t a b -> 'Control.Lens.Type.Setter' s t a b+-- @+toSetter :: Settable f => OpticP (Star f) s t a b -> LensLike f s t a b+toSetter p = runStar . p . Star++-- | Obtain a 'Control.Lens.Type.Traversal' from a 'Profunctor'-based one.+--+-- @+-- 'toTraversal' :: TraversalP s t a b -> 'Control.Lens.Type.Traversal' s t a b+-- @+toTraversal :: Applicative f => OpticP (Star f) s t a b -> LensLike f s t a b+toTraversal p = runStar . p . Star
− src/Control/Lens/Projection.hs
@@ -1,74 +0,0 @@-{-# LANGUAGE GADTs #-}-{-# LANGUAGE Rank2Types #-}-{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FlexibleInstances #-}----------------------------------------------------------------------------------- |--- Module      :  Control.Lens.Projection--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  non-portable------------------------------------------------------------------------------------module Control.Lens.Projection-  ( Projection-  , Projective(..)-  , project-  , by-  , Project(..)-  , projection-  , stereo-  , mirror-  -- * Simple-  , SimpleProjection-  ) where--import Control.Applicative-import Control.Lens.Type-import Control.Lens.Getter-import Data.Functor.Identity-import Control.Lens.Iso---- | A 'Projection' is a 'Traversal' that can also be turned around with 'by' to obtain a 'Getter'-type Projection a b c d = forall k f. (Projective k a d, Applicative f) => k (c -> f d) (a -> f a)---- | Used to provide overloading of projections.-class Projective k a d where-  projective :: (d -> a) -> (x -> y) -> k x y--instance Projective (->) a d where-  projective _ x = x---- | A concrete 'Projection', suitable for storing in a container or extracting an embedding.-data Project a d x y = Project (d -> a) (x -> y)---- | Compose projections.-stereo :: Projective k a c => Project b c y z -> Project a b x y -> k x z-stereo (Project g f) (Project i h) = projective (i.g) (f.h)--instance (a ~ a', d ~ d') => Projective (Project a d) a' d' where-  projective = Project---- | Reflect a 'Projection'.-project :: Projective k a d => Overloaded (Project a d) f a a c d -> Overloaded k f a a c d-project (Project f g) = projective f g---- | Turn a 'Projection' around to get an embedding-by :: Project a d (d -> Identity d) (a -> Identity a) -> Getter d a-by (Project g _) = to g---- | Build a 'Projection'-projection :: (d -> a) -> (a -> Maybe c) -> Projection a b c d-projection da amc = projective da (\cfd a -> maybe (pure a) (fmap da . cfd) (amc a))---- | Convert an 'Iso' to a 'Projection'.------ Ideally we would be able to use an 'Iso' directly as a 'Projection', but this opens a can of worms.-mirror :: Projective k a c => Simple Iso a c -> Simple Projection a c-mirror l = projection (^.from l) (\a -> Just (a^.l))---- | @type 'SimpleProjection' = 'Simple' 'Projection'@-type SimpleProjection a b = Projection a a b b
+ src/Control/Lens/Reified.hs view
@@ -0,0 +1,536 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE TypeFamilies #-}+------------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Reified+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  Rank2Types+--+------------------------------------------------------------------------------+module Control.Lens.Reified where++import Control.Applicative+import Control.Arrow+import qualified Control.Category as Cat+import Control.Comonad+import Control.Lens.Fold+import Control.Lens.Getter+import Control.Lens.Internal.Indexed+import Control.Lens.Traversal (ignored)+import Control.Lens.Type+import Control.Monad+import Control.Monad.Reader.Class+import Data.Distributive+import Data.Foldable+import Data.Functor.Compose+import Data.Functor.Contravariant+import Data.Functor.Bind+import Data.Functor.Extend+import Data.Functor.Identity+import Data.Functor.Plus+import Data.Profunctor.Closed+import Data.Profunctor+import Data.Profunctor.Rep+import Data.Profunctor.Sieve+#if !(MIN_VERSION_base(4,11,0))+import Data.Semigroup+#endif++-- $setup+-- >>> import Control.Lens+-- >>> import Control.Applicative++------------------------------------------------------------------------------+-- Lens+------------------------------------------------------------------------------++-- | Reify a t'Lens' so it can be stored safely in a container.+newtype ReifiedLens s t a b = Lens { runLens :: Lens s t a b }++-- | @+-- type 'ReifiedLens'' = 'Simple' 'ReifiedLens'+-- @+type ReifiedLens' s a = ReifiedLens s s a a++------------------------------------------------------------------------------+-- IndexedLens+------------------------------------------------------------------------------++-- | Reify an t'IndexedLens' so it can be stored safely in a container.+newtype ReifiedIndexedLens i s t a b = IndexedLens { runIndexedLens :: IndexedLens i s t a b }++-- | @+-- type 'ReifiedIndexedLens'' i = 'Simple' ('ReifiedIndexedLens' i)+-- @+type ReifiedIndexedLens' i s a = ReifiedIndexedLens i s s a a++------------------------------------------------------------------------------+-- IndexedTraversal+------------------------------------------------------------------------------++-- | Reify an t'IndexedTraversal' so it can be stored safely in a container.+newtype ReifiedIndexedTraversal i s t a b = IndexedTraversal { runIndexedTraversal :: IndexedTraversal i s t a b }++-- | @+-- type 'ReifiedIndexedTraversal'' i = 'Simple' ('ReifiedIndexedTraversal' i)+-- @+type ReifiedIndexedTraversal' i s a = ReifiedIndexedTraversal i s s a a++------------------------------------------------------------------------------+-- Traversal+------------------------------------------------------------------------------++-- | A form of t'Traversal' that can be stored monomorphically in a container.+newtype ReifiedTraversal s t a b = Traversal { runTraversal :: Traversal s t a b }++-- | @+-- type 'ReifiedTraversal'' = 'Simple' 'ReifiedTraversal'+-- @+type ReifiedTraversal' s a = ReifiedTraversal s s a a++------------------------------------------------------------------------------+-- Getter+------------------------------------------------------------------------------++-- | Reify a t'Getter' so it can be stored safely in a container.+--+-- This can also be useful when combining getters in novel ways, as+-- 'ReifiedGetter' is isomorphic to '(->)' and provides similar instances.+--+-- >>> ("hello","world","!!!")^.runGetter ((,) <$> Getter _2 <*> Getter (_1.to length))+-- ("world",5)+newtype ReifiedGetter s a = Getter { runGetter :: Getter s a }++instance Distributive (ReifiedGetter s) where+  distribute as = Getter $ to $ \s -> fmap (\(Getter l) -> view l s) as++instance Functor (ReifiedGetter s) where+  fmap f l = Getter (runGetter l.to f)+  {-# INLINE fmap #-}++instance Semigroup s => Extend (ReifiedGetter s) where+  duplicated (Getter l) = Getter $ to $ \m -> Getter $ to $ \n -> view l (m <> n)+  {-# INLINE duplicated #-}++instance Monoid s => Comonad (ReifiedGetter s) where+  extract (Getter l) = view l mempty+  {-# INLINE extract #-}+  duplicate (Getter l) = Getter $ to $ \m -> Getter $ to $ \n -> view l (mappend m n)+  {-# INLINE duplicate #-}++instance Monoid s => ComonadApply (ReifiedGetter s) where+  Getter mf <@> Getter ma = Getter $ to $ \s -> view mf s (view ma s)+  {-# INLINE (<@>) #-}+  m <@ _ = m+  {-# INLINE (<@) #-}+  _ @> m = m+  {-# INLINE (@>) #-}++instance Apply (ReifiedGetter s) where+  Getter mf <.> Getter ma = Getter $ to $ \s -> view mf s (view ma s)+  {-# INLINE (<.>) #-}+  m <. _ = m+  {-# INLINE (<.) #-}+  _ .> m = m+  {-# INLINE (.>) #-}++instance Applicative (ReifiedGetter s) where+  pure a = Getter $ to $ \_ -> a+  {-# INLINE pure #-}+  Getter mf <*> Getter ma = Getter $ to $ \s -> view mf s (view ma s)+  {-# INLINE (<*>) #-}+  m <* _ = m+  {-# INLINE (<*) #-}+  _ *> m = m+  {-# INLINE (*>) #-}++instance Bind (ReifiedGetter s) where+  Getter ma >>- f = Getter $ to $ \s -> view (runGetter (f (view ma s))) s+  {-# INLINE (>>-) #-}++instance Monad (ReifiedGetter s) where+  return = pure+  {-# INLINE return #-}+  Getter ma >>= f = Getter $ to $ \s -> view (runGetter (f (view ma s))) s+  {-# INLINE (>>=) #-}++instance MonadReader s (ReifiedGetter s) where+  ask = Getter id+  {-# INLINE ask #-}+  local f m = Getter (to f . runGetter m)+  {-# INLINE local #-}++instance Profunctor ReifiedGetter where+  dimap f g l = Getter $ to f.runGetter l.to g+  {-# INLINE dimap #-}+  lmap g l    = Getter $ to g.runGetter l+  {-# INLINE lmap #-}+  rmap f l    = Getter $ runGetter l.to f+  {-# INLINE rmap #-}++instance Closed ReifiedGetter where+  closed l = Getter $ to $ \f -> view (runGetter l) . f++instance Cosieve ReifiedGetter Identity where+  cosieve (Getter l) = view l . runIdentity++instance Corepresentable ReifiedGetter where+  type Corep ReifiedGetter = Identity+  cotabulate f = Getter $ to (f . Identity)++instance Sieve ReifiedGetter Identity where+  sieve (Getter l) = Identity . view l++instance Representable ReifiedGetter where+  type Rep ReifiedGetter = Identity+  tabulate f = Getter $ to (runIdentity . f)++instance Costrong ReifiedGetter where+  unfirst l = Getter $ to $ unfirst $ view (runGetter l)++instance Conjoined ReifiedGetter++instance Strong ReifiedGetter where+  first' l = Getter $ \f (s,c) ->+    phantom $ runGetter l (dimap (flip (,) c) phantom f) s+  {-# INLINE first' #-}+  second' l = Getter $ \f (c,s) ->+    phantom $ runGetter l (dimap ((,) c) phantom f) s+  {-# INLINE second' #-}++instance Choice ReifiedGetter where+  left' l = Getter $ to $ left' $ view $ runGetter l+  {-# INLINE left' #-}+  right' l = Getter $ to $ right' $ view $ runGetter l+  {-# INLINE right' #-}++instance Cat.Category ReifiedGetter where+  id = Getter id+  l . r = Getter (runGetter r.runGetter l)+  {-# INLINE (.) #-}++instance Arrow ReifiedGetter where+  arr f = Getter (to f)+  {-# INLINE arr #-}+  first l = Getter $ to $ first $ view $ runGetter l+  {-# INLINE first #-}+  second l = Getter $ to $ second $ view $ runGetter l+  {-# INLINE second #-}+  Getter l *** Getter r = Getter $ to $ view l *** view r+  {-# INLINE (***) #-}+  Getter l &&& Getter r = Getter $ to $ view l &&& view r+  {-# INLINE (&&&) #-}++instance ArrowApply ReifiedGetter where+  app = Getter $ to $ \(Getter bc, b) -> view bc b+  {-# INLINE app #-}++instance ArrowChoice ReifiedGetter where+  left l = Getter $ to $ left $ view $ runGetter l+  {-# INLINE left #-}+  right l = Getter $ to $ right $ view $ runGetter l+  {-# INLINE right #-}+  Getter l +++ Getter r = Getter $ to $ view l +++ view r+  {-# INLINE (+++) #-}+  Getter l ||| Getter r = Getter $ to $ view l ||| view r+  {-# INLINE (|||) #-}++instance ArrowLoop ReifiedGetter where+  loop l = Getter $ to $ loop $ view $ runGetter l+  {-# INLINE loop #-}++------------------------------------------------------------------------------+-- IndexedGetter+------------------------------------------------------------------------------++-- | Reify an t'IndexedGetter' so it can be stored safely in a container.+newtype ReifiedIndexedGetter i s a = IndexedGetter { runIndexedGetter :: IndexedGetter i s a }++instance Profunctor (ReifiedIndexedGetter i) where+  dimap f g l = IndexedGetter (to f . runIndexedGetter l . to g)+  {-# INLINE dimap #-}++instance Sieve (ReifiedIndexedGetter i) ((,) i) where+  sieve (IndexedGetter l) = iview l+  {-# INLINE sieve #-}++instance Representable (ReifiedIndexedGetter i) where+  type Rep (ReifiedIndexedGetter i) = (,) i+  tabulate f = IndexedGetter $ ito f+  {-# INLINE tabulate #-}++instance Strong (ReifiedIndexedGetter i) where+  first' l = IndexedGetter $ \f (s,c) ->+    phantom $ runIndexedGetter l (dimap (flip (,) c) phantom f) s+  {-# INLINE first' #-}+  second' l = IndexedGetter $ \f (c,s) ->+    phantom $ runIndexedGetter l (dimap ((,) c) phantom f) s+  {-# INLINE second' #-}++instance Functor (ReifiedIndexedGetter i s) where+  fmap f l = IndexedGetter (runIndexedGetter l.to f)+  {-# INLINE fmap #-}++instance Semigroup i => Apply (ReifiedIndexedGetter i s) where+  IndexedGetter mf <.> IndexedGetter ma = IndexedGetter $ \k s ->+    case iview mf s of+      (i, f) -> case iview ma s of+        (j, a) -> phantom $ indexed k (i <> j) (f a)+  {-# INLINE (<.>) #-}+++------------------------------------------------------------------------------+-- Fold+------------------------------------------------------------------------------++-- | Reify a t'Fold' so it can be stored safely in a container.+--+-- This can also be useful for creatively combining folds as+-- @'ReifiedFold' s@ is isomorphic to @ReaderT s []@ and provides similar+-- instances.+--+-- >>> ("hello","world")^..runFold ((,) <$> Fold _2 <*> Fold both)+-- [("world","hello"),("world","world")]+newtype ReifiedFold s a = Fold { runFold :: Fold s a }++instance Profunctor ReifiedFold where+  dimap f g l = Fold (to f . runFold l . to g)+  {-# INLINE dimap #-}+  rmap g l = Fold (runFold l . to g)+  {-# INLINE rmap #-}+  lmap f l = Fold (to f . runFold l)+  {-# INLINE lmap #-}++instance Sieve ReifiedFold [] where+  sieve (Fold l) = toListOf l++instance Representable ReifiedFold where+  type Rep ReifiedFold = []+  tabulate f = Fold (folding f)++instance Strong ReifiedFold where+  first' l = Fold $ \f (s,c) ->+    phantom $ runFold l (dimap (flip (,) c) phantom f) s+  {-# INLINE first' #-}+  second' l = Fold $ \f (c,s) ->+    phantom $ runFold l (dimap ((,) c) phantom f) s+  {-# INLINE second' #-}++instance Choice ReifiedFold where+  left' (Fold l) = Fold $ folding $ \esc -> case esc of+    Left s -> Left <$> toListOf l s+    Right c -> [Right c]+  {-# INLINE left' #-}+  right' (Fold l) = Fold $ folding $ \ecs -> case ecs of+    Left c -> [Left c]+    Right s -> Right <$> toListOf l s+  {-# INLINE right' #-}++instance Cat.Category ReifiedFold where+  id = Fold id+  l . r = Fold (runFold r . runFold l)+  {-# INLINE (.) #-}++instance Arrow ReifiedFold where+  arr f = Fold (to f)+  {-# INLINE arr #-}+  first = first'+  {-# INLINE first #-}+  second = second'+  {-# INLINE second #-}+  Fold l *** Fold r = Fold $ folding $ \(x,y) -> (,) <$> toListOf l x <*> toListOf r y+  {-# INLINE (***) #-}+  Fold l &&& Fold r = Fold $ folding $ \x -> (,) <$> toListOf l x <*> toListOf r x+  {-# INLINE (&&&) #-}++instance ArrowChoice ReifiedFold where+  left = left'+  {-# INLINE left #-}+  right = right'+  {-# INLINE right #-}++instance ArrowApply ReifiedFold where+  app = Fold $ folding $ \(Fold bc, b) -> toListOf bc b+  {-# INLINE app #-}++instance Functor (ReifiedFold s) where+  fmap f l = Fold (runFold l.to f)+  {-# INLINE fmap #-}++instance Apply (ReifiedFold s) where+  Fold mf <.> Fold ma = Fold $ folding $ \s -> toListOf mf s <.> toListOf ma s+  {-# INLINE (<.>) #-}+  Fold mf <. Fold ma = Fold $ folding $ \s -> toListOf mf s <. toListOf ma s+  {-# INLINE (<.) #-}+  Fold mf .> Fold ma = Fold $ folding $ \s -> toListOf mf s .> toListOf ma s+  {-# INLINE (.>) #-}++instance Applicative (ReifiedFold s) where+  pure a = Fold $ folding $ \_ -> [a]+  {-# INLINE pure #-}+  Fold mf <*> Fold ma = Fold $ folding $ \s -> toListOf mf s <*> toListOf ma s+  {-# INLINE (<*>) #-}+  Fold mf <* Fold ma = Fold $ folding $ \s -> toListOf mf s <* toListOf ma s+  {-# INLINE (<*) #-}+  Fold mf *> Fold ma = Fold $ folding $ \s -> toListOf mf s *> toListOf ma s+  {-# INLINE (*>) #-}++instance Alternative (ReifiedFold s) where+  empty = Fold ignored+  {-# INLINE empty #-}+  Fold ma <|> Fold mb = Fold $ folding (\s -> toListOf ma s ++ toListOf mb s)+  {-# INLINE (<|>) #-}++instance Bind (ReifiedFold s) where+  Fold ma >>- f = Fold $ folding $ \s -> toListOf ma s >>- \a -> toListOf (runFold (f a)) s+  {-# INLINE (>>-) #-}++instance Monad (ReifiedFold s) where+  return = pure+  {-# INLINE return #-}+  Fold ma >>= f = Fold $ folding $ \s -> toListOf ma s >>= \a -> toListOf (runFold (f a)) s+  {-# INLINE (>>=) #-}++instance MonadPlus (ReifiedFold s) where+  mzero = empty+  {-# INLINE mzero #-}+  mplus = (<|>)+  {-# INLINE mplus #-}++instance MonadReader s (ReifiedFold s) where+  ask = Fold id+  {-# INLINE ask #-}+  local f m = Fold (to f . runFold m)+  {-# INLINE local #-}++instance Semigroup (ReifiedFold s a) where+  (<>) = (<|>)+  {-# INLINE (<>) #-}++instance Monoid (ReifiedFold s a) where+  mempty = Fold ignored+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  mappend = (<|>)+  {-# INLINE mappend #-}+#endif++instance Alt (ReifiedFold s) where+  (<!>) = (<|>)+  {-# INLINE (<!>) #-}++instance Plus (ReifiedFold s) where+  zero = Fold ignored+  {-# INLINE zero #-}++------------------------------------------------------------------------------+-- IndexedFold+------------------------------------------------------------------------------++newtype ReifiedIndexedFold i s a = IndexedFold { runIndexedFold :: IndexedFold i s a }++instance Semigroup (ReifiedIndexedFold i s a) where+  (<>) = (<!>)+  {-# INLINE (<>) #-}++instance Monoid (ReifiedIndexedFold i s a) where+  mempty = IndexedFold ignored+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  mappend = (<!>)+  {-# INLINE mappend #-}+#endif++instance Alt (ReifiedIndexedFold i s) where+  IndexedFold ma <!> IndexedFold mb = IndexedFold $+    ifolding $ \s -> itoListOf ma s ++ itoListOf mb s+  {-# INLINE (<!>) #-}++instance Plus (ReifiedIndexedFold i s) where+  zero = IndexedFold ignored+  {-# INLINE zero #-}++instance Functor (ReifiedIndexedFold i s) where+  fmap f l = IndexedFold (runIndexedFold l . to f)+  {-# INLINE fmap #-}++instance Profunctor (ReifiedIndexedFold i) where+  dimap f g l = IndexedFold (to f . runIndexedFold l . to g)+  {-# INLINE dimap #-}+  lmap f l = IndexedFold (to f . runIndexedFold l)+  {-# INLINE lmap #-}+  rmap g l = IndexedFold (runIndexedFold l . to g)+  {-# INLINE rmap #-}++instance Sieve (ReifiedIndexedFold i) (Compose [] ((,) i)) where+  sieve (IndexedFold l) = Compose . itoListOf l+  {-# INLINE sieve #-}++instance Representable (ReifiedIndexedFold i) where+  type Rep (ReifiedIndexedFold i) = Compose [] ((,) i)+  tabulate k = IndexedFold $ \f -> phantom . traverse_ (phantom . uncurry (indexed f)) . getCompose . k+  {-# INLINE tabulate #-}++instance Strong (ReifiedIndexedFold i) where+  first' l  = IndexedFold $ \f (s,c) ->+    phantom $ runIndexedFold l (dimap (flip (,) c) phantom f) s+  {-# INLINE first' #-}+  second' l = IndexedFold $ \f (c,s) ->+    phantom $ runIndexedFold l (dimap ((,) c) phantom f) s+  {-# INLINE second' #-}+++------------------------------------------------------------------------------+-- Setter+------------------------------------------------------------------------------++-- | Reify a t'Setter' so it can be stored safely in a container.+newtype ReifiedSetter s t a b = Setter { runSetter :: Setter s t a b }++-- | @+-- type 'ReifiedSetter'' = 'Simple' 'ReifiedSetter'+-- @+type ReifiedSetter' s a = ReifiedSetter s s a a++------------------------------------------------------------------------------+-- IndexedSetter+------------------------------------------------------------------------------++-- | Reify an t'IndexedSetter' so it can be stored safely in a container.+newtype ReifiedIndexedSetter i s t a b =+  IndexedSetter { runIndexedSetter :: IndexedSetter i s t a b }++-- | @+-- type 'ReifiedIndexedSetter'' i = 'Simple' ('ReifiedIndexedSetter' i)+-- @+type ReifiedIndexedSetter' i s a = ReifiedIndexedSetter i s s a a++------------------------------------------------------------------------------+-- Iso+------------------------------------------------------------------------------++-- | Reify an t'Iso' so it can be stored safely in a container.+newtype ReifiedIso s t a b = Iso { runIso :: Iso s t a b }++-- | @+-- type 'ReifiedIso'' = 'Simple' 'ReifiedIso'+-- @+type ReifiedIso' s a = ReifiedIso s s a a++------------------------------------------------------------------------------+-- Prism+------------------------------------------------------------------------------++-- | Reify a t'Prism' so it can be stored safely in a container.+newtype ReifiedPrism s t a b = Prism { runPrism :: Prism s t a b }++-- | @+-- type 'ReifiedPrism'' = 'Simple' 'ReifiedPrism'+-- @+type ReifiedPrism' s a = ReifiedPrism s s a a
− src/Control/Lens/Representable.hs
@@ -1,313 +0,0 @@-{-# LANGUAGE RankNTypes #-}-{-# LANGUAGE FlexibleContexts #-}--------------------------------------------------------------------------------- |--- Module      :  Control.Lens.Representable--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  RankNTypes------ Corepresentable endofunctors represented by their polymorphic lenses------ The polymorphic lenses of the form @(forall x. 'Lens' (f x) x)@ each--- represent a distinct path into a functor @f@. If the functor is entirely--- characterized by assigning values to these paths, then the functor is--- representable.------ Consider the following example.------ > import Control.Lens--- > import Data.Distributive------ > data Pair a = Pair { _x :: a, _y :: a }------ @ 'Control.Lens.TH.makeLenses' \'\'Pair@------ @--- instance 'Representable' Pair where---   'rep' f = Pair (f x) (f y)--- @------ From there, you can get definitions for a number of instances for free.------ @--- instance 'Applicative' Pair where---   'pure'  = 'pureRep'---   ('<*>') = 'apRep'--- @------ @--- instance 'Monad' Pair where---   'return' = 'pureRep'---   ('>>=') = 'bindRep'--- @------ @--- instance 'Data.Distributive.Distributive' Pair where---   'Data.Distributive.distribute' = 'distributeRep'--- @---------------------------------------------------------------------------------module Control.Lens.Representable-  (-  -- * Representable Functors-    Representable(..)-  -- * Using Lenses as Representations-  , Rep-  -- * Default definitions-  , fmapRep-  , pureRep-  , apRep-  , bindRep-  , distributeRep-  -- * Wrapped Representations-  , Path(..)-  , paths-  , tabulated-  -- * Setting with Representation-  , rmap-  -- * Folding with Representation-  , rfoldMap-  , rfoldr-  -- * Traversing with Representation-  , rtraverse-  , rtraverse_-  , rfor-  , rmapM-  , rmapM_-  , rforM-  -- * Representable Setters, Folds and Traversals-  , rmapped-  , rfolded-  , rtraversed-  ) where--import Control.Applicative-import Control.Lens.Iso-import Control.Lens.Type-import Control.Lens.Getter-import Control.Lens.Indexed-import Control.Lens.IndexedSetter-import Control.Lens.IndexedFold-import Control.Lens.IndexedTraversal-import Control.Lens.Internal-import Data.Foldable         as Foldable-import Data.Functor.Identity-import Data.Monoid-import Data.Traversable      as Traversable---- | The representation of a 'Representable' 'Functor' as Lenses-type Rep f = forall a. Simple Lens (f a) a---- | Representable Functors.------ A 'Functor' @f@ is 'Representable' if it is isomorphic to @(x -> a)@--- for some x. Nearly all such functors can be represented by choosing @x@ to be--- the set of lenses that are polymorphic in the contents of the 'Functor',--- that is to say @x = 'Rep' f@ is a valid choice of 'x' for (nearly) every--- 'Representable' 'Functor'.------ Note: Some sources refer to covariant representable functors as--- corepresentable functors, and leave the \"representable\" name to--- contravariant functors (those are isomorphic to @(a -> x)@ for some @x@).------ As the covariant case is vastly more common, and both are often referred to--- as representable functors, we choose to call these functors 'Representable'--- here.-class Functor f => Representable f where-  rep :: (Rep f -> a) -> f a--instance Representable Identity where-  rep f = Identity (f (from identity))---- | NB: The 'Eq' requirement on this instance is a consequence of the choice of 'Lens' as a 'Rep', it isn't fundamental.-instance Eq e => Representable ((->) e) where-  rep f e = f (resultAt e)---- | 'fmapRep' is a valid default definition for 'fmap' for a 'Representable'--- functor.------ @'fmapRep' f m = 'rep' '$' \i -> f (m '^.' i)@------ Usage for a @'Representable' Foo@:------ @--- instance 'Functor' Foo where---   'fmap' = 'fmapRep'--- @-fmapRep :: Representable f => (a -> b) -> f a -> f b-fmapRep f m = rep $ \i -> f (m^.i)-{-# INLINE fmapRep #-}---- | 'pureRep' is a valid default definition for 'pure' and 'return' for a--- 'Representable' functor.------ @'pureRep' = 'rep' . 'const'@------ Usage for a @'Representable' Foo@:------ @--- instance 'Applicative' Foo where---   'pure' = 'pureRep'---   ...--- @------ @--- instance 'Monad' Foo where---   'return' = 'pureRep'---   ...--- @-pureRep :: Representable f => a -> f a-pureRep = rep . const-{-# INLINE pureRep #-}---- | 'apRep' is a valid default definition for ('<*>') for a 'Representable'--- functor.------ @'apRep' mf ma = 'rep' '$' \i -> mf '^.' i '$' ma '^.' i@------ Usage for a @'Representable' Foo@:------ @--- instance 'Applicative' Foo where---   'pure' = 'pureRep'---   ('<*>') = 'apRep'--- @-apRep :: Representable f => f (a -> b) -> f a -> f b-apRep mf ma = rep $ \i -> mf^.i $ ma^.i-{-# INLINE apRep #-}---- | 'bindRep' is a valid default default definition for '(>>=)' for a--- representable functor.------ @'bindRep' m f = 'rep' '$' \i -> f (m '^.' i) '^.' i@------ Usage for a @'Representable' Foo@:------ @--- instance 'Monad' Foo where---   'return' = 'pureRep'---   ('>>=') = 'bindRep'--- @-bindRep :: Representable f => f a -> (a -> f b) -> f b-bindRep m f = rep $ \i -> f(m^.i)^.i-{-# INLINE bindRep #-}---- | A default definition for 'Data.Distributive.distribute' for a 'Representable' 'Functor'------ @'distributeRep' wf = 'rep' '$' \i -> 'fmap' ('^.' i) wf@------ Usage for a @'Representable' Foo@:------ @--- instance 'Data.Distributive.Distributive' Foo where---   'Data.Distributive.distribute' = 'distributeRep'--- @-distributeRep :: (Representable f, Functor w) => w (f a) -> f (w a)-distributeRep wf = rep $ \i -> fmap (^.i) wf-{-# INLINE distributeRep #-}---------------------------------------------------------------------------------- Paths---------------------------------------------------------------------------------- | Sometimes you need to store a path lens into a container, but at least--- at this time, @ImpredicativePolymorphism@ in GHC is somewhat lacking.------ This type provides a way to, say, store a @[]@ of paths.-newtype Path f = Path { walk :: Rep f }---- | A 'Representable' 'Functor' has a fixed shape. This fills each position--- in it with a 'Path'-paths :: Representable f => f (Path f)-paths = rep Path-{-# INLINE paths #-}---- | A version of 'rep' that is an isomorphism. Predicativity requires that--- we wrap the 'Rep' as a 'Key', however.-tabulated :: Representable f => (Path f -> a) -> f a-tabulated = isomorphic (\f -> rep (f . Path)) (\fa path -> view (walk path) fa)-{-# INLINE tabulated #-}---------------------------------------------------------------------------------- Traversal---------------------------------------------------------------------------------- | Map over a 'Representable' functor with access to the 'Lens' for the--- current position------ @'rmap' f m = 'rep' '$' \i -> f i (m '^.' i)@-rmap :: Representable f => (Rep f -> a -> b) -> f a -> f b-rmap f m = rep $ \i -> f i (m^.i)-{-# INLINE rmap #-}---- | Traverse a 'Representable' functor with access to the current path-rtraverse :: (Representable f, Traversable f, Applicative g)-          => (Rep f -> a -> g b) -> f a -> g (f b)-rtraverse f m = sequenceA (rmap f m)-{-# INLINE rtraverse #-}---- | Traverse a 'Representable' functor with access to the current path--- as a 'Lens', discarding the result-rtraverse_ :: (Representable f, Foldable f, Applicative g)-           => (Rep f -> a -> g b) -> f a -> g ()-rtraverse_ f m = sequenceA_ (rmap f m)-{-# INLINE rtraverse_ #-}---- | Traverse a 'Representable' functor with access to the current path--- and a 'Lens' (and the arguments flipped)-rfor :: (Representable f, Traversable f, Applicative g)-     => f a -> (Rep f -> a -> g b) -> g (f b)-rfor m f = sequenceA (rmap f m)-{-# INLINE rfor #-}---- | 'mapM' over a 'Representable' functor with access to the current path--- as a 'Lens'-rmapM :: (Representable f, Traversable f, Monad m)-      => (Rep f -> a -> m b) -> f a -> m (f b)-rmapM f m = Traversable.sequence (rmap f m)-{-# INLINE rmapM #-}---- | 'mapM' over a 'Representable' functor with access to the current path--- as a 'Lens', discarding the result-rmapM_ :: (Representable f, Foldable f, Monad m)-       => (Rep f -> a -> m b) -> f a -> m ()-rmapM_ f m = Foldable.sequence_ (rmap f m)-{-# INLINE rmapM_ #-}---- | 'mapM' over a 'Representable' functor with access to the current path--- as a 'Lens' (with the arguments flipped)-rforM :: (Representable f, Traversable f, Monad m)-      => f a -> (Rep f -> a -> m b) -> m (f b)-rforM m f = Traversable.sequence (rmap f m)-{-# INLINE rforM #-}---- | Fold over a 'Representable' functor with access to the current path--- as a 'Lens', yielding a 'Monoid'-rfoldMap :: (Representable f, Foldable f, Monoid m)-         => (Rep f -> a -> m) -> f a -> m-rfoldMap f m = fold (rmap f m)-{-# INLINE rfoldMap #-}---- | Fold over a 'Representable' functor with access to the current path--- as a 'Lens'.-rfoldr :: (Representable f, Foldable f) => (Rep f -> a -> b -> b) -> b -> f a -> b-rfoldr f b m = Foldable.foldr id b (rmap f m)-{-# INLINE rfoldr #-}---- | An 'IndexedSetter' that walks an 'Representable' 'Functor' using a 'Path' for an index.-rmapped :: Representable f => IndexedSetter (Path f) (f a) (f b) a b-rmapped = index $ \f -> pure . rmap (\i -> untainted . f (Path i))-{-# INLINE rmapped #-}---- | An 'IndexedFold' that walks an 'Foldable' 'Representable' 'Functor' using a 'Path' for an index.-rfolded :: (Representable f, Foldable f) => IndexedFold (Path f) (f a) a-rfolded = index $ \f -> coerce . getFolding . rfoldMap (\i -> Folding . f (Path i))-{-# INLINE rfolded #-}---- | An 'IndexedTraversal' for a 'Traversable' 'Representable' 'Functor'.-rtraversed :: (Representable f, Traversable f) => IndexedTraversal (Path f) (f a) (f b) a b-rtraversed = index $ \ f -> sequenceA . rmap (f . Path)-{-# INLINE rtraversed #-}
+ src/Control/Lens/Review.hs view
@@ -0,0 +1,253 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE Trustworthy #-}++{-# OPTIONS_GHC -Wno-redundant-constraints -Wno-trustworthy-safe #-}+-------------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Review+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  non-portable+--+-- A 'Review' is a type-restricted form of a 'Prism' that can only be used for+-- writing back via 're', 'review', 'reuse'.+-------------------------------------------------------------------------------+module Control.Lens.Review+  (+  -- * Reviewing+    Review+  , AReview+  , unto+  , un+  , re+  , review, reviews+  , reuse, reuses+  , (#)+  , Bifunctor(bimap)+  , retagged+  , Reviewable+  , reviewing+  ) where++import Control.Monad.Reader as Reader+import Control.Monad.State as State+import Control.Lens.Getter+import Control.Lens.Internal.Review+import Control.Lens.Type+import Data.Bifunctor+import Data.Functor.Identity+import Data.Profunctor+import Data.Profunctor.Unsafe+import Data.Tagged+import Data.Void++-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import Control.Monad.State+-- >>> import Numeric.Lens+-- >>> import Data.Semigroup (Semigroup (..))+-- >>> let isLeft  (Left  _) = True; isLeft  _ = False+-- >>> let isRight (Right _) = True; isRight _ = False++infixr 8 #++------------------------------------------------------------------------------+-- Review+------------------------------------------------------------------------------++-- | An analogue of 'to' for 'review'.+--+-- @+-- 'unto' :: (b -> t) -> 'Review'' t b+-- @+--+-- @+-- 'unto' = 'un' . 'to'+-- @+unto :: (Profunctor p, Bifunctor p, Functor f) => (b -> t) -> Optic p f s t a b+unto f = first absurd . lmap absurd . rmap (fmap f)+{-# INLINE unto #-}++-- | Turn a 'Getter' around to get a 'Review'+--+-- @+-- 'un' = 'unto' . 'view'+-- 'unto' = 'un' . 'to'+-- @+--+-- >>> un (to length) # [1,2,3]+-- 3+un :: (Profunctor p, Bifunctor p, Functor f) => Getting a s a -> Optic' p f a s+un = unto . view++-- | Turn a 'Prism' or 'Control.Lens.Iso.Iso' around to build a 'Getter'.+--+-- If you have an 'Control.Lens.Iso.Iso', 'Control.Lens.Iso.from' is a more powerful version of this function+-- that will return an 'Control.Lens.Iso.Iso' instead of a mere 'Getter'.+--+-- >>> 5 ^.re _Left+-- Left 5+--+-- >>> 6 ^.re (_Left.unto succ)+-- Left 7+--+-- @+-- 'review'  ≡ 'view'  '.' 're'+-- 'reviews' ≡ 'views' '.' 're'+-- 'reuse'   ≡ 'use'   '.' 're'+-- 'reuses'  ≡ 'uses'  '.' 're'+-- @+--+-- @+-- 're' :: 'Prism' s t a b -> 'Getter' b t+-- 're' :: 'Iso' s t a b   -> 'Getter' b t+-- @+re :: AReview t b -> Getter b t+re p = to (runIdentity #. unTagged #. p .# Tagged .# Identity)+{-# INLINE re #-}++-- | This can be used to turn an 'Control.Lens.Iso.Iso' or 'Prism' around and 'view' a value (or the current environment) through it the other way.+--+-- @+-- 'review' ≡ 'view' '.' 're'+-- 'review' . 'unto' ≡ 'id'+-- @+--+-- >>> review _Left "mustard"+-- Left "mustard"+--+-- >>> review (unto succ) 5+-- 6+--+-- Usually 'review' is used in the @(->)@ 'Monad' with a 'Prism' or 'Control.Lens.Iso.Iso', in which case it may be useful to think of+-- it as having one of these more restricted type signatures:+--+-- @+-- 'review' :: 'Iso'' s a   -> a -> s+-- 'review' :: 'Prism'' s a -> a -> s+-- @+--+-- However, when working with a 'Monad' transformer stack, it is sometimes useful to be able to 'review' the current environment, in which case+-- it may be beneficial to think of it as having one of these slightly more liberal type signatures:+--+-- @+-- 'review' :: 'MonadReader' a m => 'Iso'' s a   -> m s+-- 'review' :: 'MonadReader' a m => 'Prism'' s a -> m s+-- @+review :: MonadReader b m => AReview t b -> m t+review p = asks (runIdentity #. unTagged #. p .# Tagged .# Identity)+{-# INLINE review #-}++-- | An infix alias for 'review'.+--+-- @+-- 'unto' f # x ≡ f x+-- l # x ≡ x '^.' 're' l+-- @+--+-- This is commonly used when using a 'Prism' as a smart constructor.+--+-- >>> _Left # 4+-- Left 4+--+-- But it can be used for any 'Prism'+--+-- >>> base 16 # 123+-- "7b"+--+-- @+-- (#) :: 'Iso''      s a -> a -> s+-- (#) :: 'Prism''    s a -> a -> s+-- (#) :: 'Review'    s a -> a -> s+-- (#) :: 'Equality'' s a -> a -> s+-- @+(#) :: AReview t b -> b -> t+(#) p = runIdentity #. unTagged #. p .# Tagged .# Identity+{-# INLINE (#) #-}++-- | This can be used to turn an 'Control.Lens.Iso.Iso' or 'Prism' around and 'view' a value (or the current environment) through it the other way,+-- applying a function.+--+-- @+-- 'reviews' ≡ 'views' '.' 're'+-- 'reviews' ('unto' f) g ≡ g '.' f+-- @+--+-- >>> reviews _Left isRight "mustard"+-- False+--+-- >>> reviews (unto succ) (*2) 3+-- 8+--+-- Usually this function is used in the @(->)@ 'Monad' with a 'Prism' or 'Control.Lens.Iso.Iso', in which case it may be useful to think of+-- it as having one of these more restricted type signatures:+--+-- @+-- 'reviews' :: 'Iso'' s a   -> (s -> r) -> a -> r+-- 'reviews' :: 'Prism'' s a -> (s -> r) -> a -> r+-- @+--+-- However, when working with a 'Monad' transformer stack, it is sometimes useful to be able to 'review' the current environment, in which case+-- it may be beneficial to think of it as having one of these slightly more liberal type signatures:+--+-- @+-- 'reviews' :: 'MonadReader' a m => 'Iso'' s a   -> (s -> r) -> m r+-- 'reviews' :: 'MonadReader' a m => 'Prism'' s a -> (s -> r) -> m r+-- @+reviews :: MonadReader b m => AReview t b -> (t -> r) -> m r+reviews p tr = asks (tr . runIdentity #. unTagged #. p .# Tagged .# Identity)+{-# INLINE reviews #-}++-- | This can be used to turn an 'Control.Lens.Iso.Iso' or 'Prism' around and 'use' a value (or the current environment) through it the other way.+--+-- @+-- 'reuse' ≡ 'use' '.' 're'+-- 'reuse' '.' 'unto' ≡ 'gets'+-- @+--+-- >>> evalState (reuse _Left) 5+-- Left 5+--+-- >>> evalState (reuse (unto succ)) 5+-- 6+--+-- @+-- 'reuse' :: 'MonadState' a m => 'Prism'' s a -> m s+-- 'reuse' :: 'MonadState' a m => 'Iso'' s a   -> m s+-- @+reuse :: MonadState b m => AReview t b -> m t+reuse p = gets (runIdentity #. unTagged #. p .# Tagged .# Identity)+{-# INLINE reuse #-}++-- | This can be used to turn an 'Control.Lens.Iso.Iso' or 'Prism' around and 'use' the current state through it the other way,+-- applying a function.+--+-- @+-- 'reuses' ≡ 'uses' '.' 're'+-- 'reuses' ('unto' f) g ≡ 'gets' (g '.' f)+-- @+--+-- >>> evalState (reuses _Left isLeft) (5 :: Int)+-- True+--+-- @+-- 'reuses' :: 'MonadState' a m => 'Prism'' s a -> (s -> r) -> m r+-- 'reuses' :: 'MonadState' a m => 'Iso'' s a   -> (s -> r) -> m r+-- @+reuses :: MonadState b m => AReview t b -> (t -> r) -> m r+reuses p tr = gets (tr . runIdentity #. unTagged #. p .# Tagged .# Identity)+{-# INLINE reuses #-}++-- | Coerce a polymorphic 'Prism' to a 'Review'.+--+-- @+-- 'reviewing' :: 'Iso' s t a b -> 'Review' t b+-- 'reviewing' :: 'Prism' s t a b -> 'Review' t b+-- @+reviewing :: (Bifunctor p, Functor f) => Optic Tagged Identity s t a b -> Optic' p f t b+reviewing p = bimap f (fmap f) where+  f = runIdentity . unTagged . p . Tagged . Identity
src/Control/Lens/Setter.hs view
@@ -1,699 +1,1384 @@-{-# LANGUAGE Rank2Types #-}-{-# LANGUAGE LiberalTypeSynonyms #-}--------------------------------------------------------------------------------- |--- Module      :  Control.Lens.Setter--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  Rank2Types------ A @'Setter' a b c d@ is a generalization of 'fmap' from 'Functor'. It allows you to map into a--- structure and change out the contents, but it isn't strong enough to allow you to--- enumerate those contents. Starting with @fmap :: 'Functor' f => (c -> d) -> f c -> f d@--- we monomorphize the type to obtain @(c -> d) -> a -> b@ and then decorate it with 'Data.Functor.Identity.Identity' to obtain------ @type 'Setter' a b c d = (c -> 'Data.Functor.Identity.Identity' d) -> a -> 'Data.Functor.Identity.Identity' b@------ Every 'Control.Lens.Traversal.Traversal' is a valid 'Setter', since 'Data.Functor.Identity.Identity' is 'Applicative'.------ Everything you can do with a 'Functor', you can do with a 'Setter'. There--- are combinators that generalize 'fmap' and ('<$').------------------------------------------------------------------------------module Control.Lens.Setter-  (-  -- * Setters-    Setter-  -- * Building Setters-  , sets-  -- * Common Setters-  , mapped-  -- * Functional Combinators-  , over-  , mapOf-  , set-  , (.~), (%~)-  , (+~), (-~), (*~), (//~), (^~), (^^~), (**~), (||~), (&&~), (<.~)-  -- * State Combinators-  , assign-  , (.=), (%=)-  , (+=), (-=), (*=), (//=), (^=), (^^=), (**=), (||=), (&&=), (<.=)-  , (<~)-  -- * Storing Setters-  , ReifiedSetter(..)-  -- * Setter Internals-  , Setting-  , SimpleSetting-  -- * Simplicity-  , SimpleSetter-  , SimpleReifiedSetter-  -- * Exported for legible error messages-  , Settable-  , Mutator-  ) where--import Control.Applicative-import Control.Lens.Internal-import Control.Monad.State.Class as State---- $setup--- >>> import Control.Lens--infixr 4 .~, +~, *~, -~, //~, ^~, ^^~, **~, &&~, ||~, %~, <.~-infix  4 .=, +=, *=, -=, //=, ^=, ^^=, **=, &&=, ||=, %=, <.=-infixr 2 <~----------------------------------------------------------------------------------- Setters----------------------------------------------------------------------------------- |--- The only 'Control.Lens.Type.Lens'-like law that can apply to a 'Setter' @l@ is that------ @'set' l c ('set' l b a) ≡ 'set' l c a@------ You can't 'view' a 'Setter' in general, so the other two laws are irrelevant.------ However, two 'Functor' laws apply to a 'Setter':------ @--- 'over' l 'id' ≡ 'id'--- 'over' l f '.' 'over' l g ≡ 'over' l (f '.' g)--- @------ These an be stated more directly:------ @--- l 'pure' ≡ 'pure'--- l f . 'untainted' . l g ≡ l (f . 'untainted' . g)--- @------ You can compose a 'Setter' with a 'Control.Lens.Type.Lens' or a 'Control.Lens.Traversal.Traversal' using ('.') from the Prelude--- and the result is always only a 'Setter' and nothing more.-type Setter a b c d = forall f. Settable f => (c -> f d) -> a -> f b---- |--- Running a 'Setter' instantiates it to a concrete type.------ When consuming a setter directly to perform a mapping, you can use this type, but most--- user code will not need to use this type.------ By choosing 'Mutator' rather than 'Data.Functor.Identity.Identity', we get nicer error messages.-type Setting a b c d = (c -> Mutator d) -> a -> Mutator b---- |------ A Simple Setter is just a 'Setter' that doesn't change the types.------ These are particularly common when talking about monomorphic containers. /e.g./------ @'sets' Data.Text.map :: 'SimpleSetter' 'Data.Text.Internal.Text' 'Char'@------ @type 'SimpleSetter' = 'Control.Lens.Type.Simple' 'Setter'@-type SimpleSetter a b = Setter a a b b---- |--- This is a useful alias for use when consuming a 'SimpleSetter'.------ Most user code will never have to use this type.------ @type 'SimpleSetting' m = 'Control.Lens.Type.Simple' 'Setting'@-type SimpleSetting a b = Setting a a b b---------------------------------------------------------------------------------- Setters---------------------------------------------------------------------------------- | This setter can be used to map over all of the values in a 'Functor'.------ @--- 'fmap' ≡ 'over' 'mapped'--- 'Data.Traversable.fmapDefault' ≡ 'over' 'Data.Traversable.traverse'--- ('<$') ≡ 'set' 'mapped'--- @------ >>> over mapped (+1) [1,2,3]--- [2,3,4]------ >>> set mapped () [1,2,3]--- [(),(),()]------ >>> mapped.mapped %~ (+1) $ [[1,2],[3]]--- [[2,3],[4]]------ >>> over (mapped._2) length [("hello","world"),("leaders","!!!")]--- [("hello",5),("leaders",3)]-mapped :: Functor f => Setter (f a) (f b) a b-mapped = sets fmap-{-# INLINE mapped #-}---- | Build a Setter from a map-like function.------ Your supplied function @f@ is required to satisfy:------ @--- f 'id' ≡ 'id'--- f g '.' f h ≡ f (g '.' h)--- @------ Equational reasoning:------ @--- 'sets' '.' 'over' ≡ 'id'--- 'over' '.' 'sets' ≡ 'id'--- @------ Another way to view 'sets' is that it takes a \"semantic editor combinator\"--- and transforms it into a 'Setter'.-sets :: ((c -> d) -> a -> b) -> Setter a b c d-sets f g = pure . f (untainted . g)-{-# INLINE sets #-}---------------------------------------------------------------------------------- Using Setters---------------------------------------------------------------------------------- | Modify the target of a 'Control.Lens.Type.Lens' or all the targets of a 'Setter' or 'Control.Lens.Traversal.Traversal'--- with a function.------ @--- 'fmap' ≡ 'over' 'mapped'--- 'Data.Traversable.fmapDefault' ≡ 'over' 'Data.Traversable.traverse'--- 'sets' '.' 'over' ≡ 'id'--- 'over' '.' 'sets' ≡ 'id'--- @------ >>> over mapped (*10) [1,2,3]--- [10,20,30]------ >>> over _1 show (10,20)--- ("10",20)------ Another way to view 'over' is to say that it transformers a 'Setter' into a--- \"semantic editor combinator\".------ @'over' :: 'Setter' a b c d -> (c -> d) -> a -> b@-over :: Setting a b c d -> (c -> d) -> a -> b-over l f = runMutator . l (Mutator . f)-{-# INLINE over #-}---- | Modify the target of a 'Control.Lens.Type.Lens' or all the targets of a 'Setter' or 'Control.Lens.Traversal.Traversal'--- with a function. This is an alias for 'over' that is provided for consistency.------ @--- 'mapOf' ≡ 'over'--- 'fmap' ≡ 'mapOf' 'mapped'--- 'fmapDefault' ≡ 'mapOf' 'traverse'--- 'sets' '.' 'mapOf' ≡ 'id'--- 'mapOf' '.' 'sets' ≡ 'id'--- @------ >>> mapOf mapped (+1) [1,2,3,4]--- [2,3,4,5]------ >>> mapOf _1 (+1) (1,2)--- (2,2)------ >>> mapOf both (+1) (1,2)--- (2,3)------ @--- 'mapOf' :: 'Setter' a b c d      -> (c -> d) -> a -> b--- 'mapOf' :: 'Control.Lens.Iso.Iso' a b c d         -> (c -> d) -> a -> b--- 'mapOf' :: 'Control.Lens.Type.Lens' a b c d        -> (c -> d) -> a -> b--- 'mapOf' :: 'Control.Lens.Traversal.Traversal' a b c d   -> (c -> d) -> a -> b--- @-mapOf :: Setting a b c d -> (c -> d) -> a -> b-mapOf = over-{-# INLINE mapOf #-}---- | Replace the target of a 'Control.Lens.Type.Lens' or all of the targets of a 'Setter'--- or 'Control.Lens.Traversal.Traversal' with a constant value.------ @('<$') ≡ 'set' 'mapped'@------ >>> set _2 "hello" (1,())--- (1,"hello")------ >>> set mapped () [1,2,3,4]--- [(),(),(),()]------ Note: Attempting to 'set' a 'Fold' or 'Getter' will fail at compile time with an--- relatively nice error message.------ @--- 'set' :: 'Setter' a b c d    -> d -> a -> b--- 'set' :: 'Control.Lens.Iso.Iso' a b c d       -> d -> a -> b--- 'set' :: 'Control.Lens.Type.Lens' a b c d      -> d -> a -> b--- 'set' :: 'Control.Lens.Traversal.Traversal' a b c d -> d -> a -> b--- @-set :: Setting a b c d -> d -> a -> b-set l d = runMutator . l (\_ -> Mutator d)-{-# INLINE set #-}---- | Modifies the target of a 'Control.Lens.Type.Lens' or all of the targets of a 'Setter' or--- 'Control.Lens.Traversal.Traversal' with a user supplied function.------ This is an infix version of 'over'------ @--- 'fmap' f ≡ 'mapped' '%~' f--- 'Data.Traversable.fmapDefault' f ≡ 'traverse' '%~' f--- @------ >>> _2 %~ length $ (1,"hello")--- (1,5)------ >>> traverse %~ (+1) $ [1,2,3]--- [2,3,4]------ >>> _2 %~ (+1) $ (3,4)--- (3,5)------ >>> traverse.traverse %~ length $ [["hello","world"],["!!!"]]--- [[5,5],[3]]------ @--- ('%~') :: 'Setter' a b c d    -> (c -> d) -> a -> b--- ('%~') :: 'Control.Lens.Iso.Iso' a b c d       -> (c -> d) -> a -> b--- ('%~') :: 'Control.Lens.Type.Lens' a b c d      -> (c -> d) -> a -> b--- ('%~') :: 'Control.Lens.Traversal.Traversal' a b c d -> (c -> d) -> a -> b--- @-(%~) :: Setting a b c d -> (c -> d) -> a -> b-(%~) = over-{-# INLINE (%~) #-}---- | Replace the target of a 'Control.Lens.Type.Lens' or all of the targets of a 'Setter'--- or 'Control.Lens.Traversal.Traversal' with a constant value.------ This is an infix version of 'set', provided for consistency with ('.=')------ @f '<$' a ≡ 'mapped' '.~' f '$' a@------ >>> _1 .~ "hello" $ (42,"world")--- ("hello","world")------ @--- ('.~') :: 'Setter' a b c d    -> d -> a -> b--- ('.~') :: 'Control.Lens.Iso.Iso' a b c d       -> d -> a -> b--- ('.~') :: 'Control.Lens.Type.Lens' a b c d      -> d -> a -> b--- ('.~') :: 'Control.Lens.Traversal.Traversal' a b c d -> d -> a -> b--- @-(.~) :: Setting a b c d -> d -> a -> b-(.~) = set-{-# INLINE (.~) #-}---- | Set with pass-through------ This is mostly present for consistency, but may be useful for for chaining assignments------ If you do not need a copy of the intermediate result, then using @l '.~' d@ directly is a good idea.------ >>> _3 <.~ "world" $ ("good","morning","vietnam")--- ("world",("good","morning","world"))------ >>> import Data.Map as Map--- >>> _2.at "hello" <.~ Just "world" $ (42,Map.fromList [("goodnight","gracie")])--- (Just "world",(42,fromList [("goodnight","gracie"),("hello","world")]))------ @--- ('<.~') :: 'Setter' a b c d    -> d -> a -> (d, b)--- ('<.~') :: 'Control.Lens.Iso.Iso' a b c d       -> d -> a -> (d, b)--- ('<.~') :: 'Control.Lens.Type.Lens' a b c d      -> d -> a -> (d, b)--- ('<.~') :: 'Control.Lens.Traversal.Traversal' a b c d -> d -> a -> (d, b)--- @-(<.~) :: Setting a b c d -> d -> a -> (d, b)-l <.~ d = \a -> (d, l .~ d $ a)-{-# INLINE (<.~) #-}---- | Increment the target(s) of a numerically valued 'Control.Lens.Type.Lens', 'Setter' or 'Control.Lens.Traversal.Traversal'------ >>> _1 +~ 1 $ (1,2)--- (2,2)------ >>> both +~ 2 $ (5,6)--- (7,8)------ @--- ('+~') :: Num b => 'Control.Lens.Type.Simple' 'Setter' a b -> b -> a -> a--- ('+~') :: Num b => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b -> b -> a -> a--- ('+~') :: Num b => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b -> b -> a -> a--- ('+~') :: Num b => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> b -> a -> a--- @-(+~) :: Num c => Setting a b c c -> c -> a -> b-l +~ n = over l (+ n)-{-# INLINE (+~) #-}---- | Multiply the target(s) of a numerically valued 'Control.Lens.Type.Lens', 'Control.Lens.Iso.Iso', 'Setter' or 'Control.Lens.Traversal.Traversal'------ >>> _2 *~ 4 $ (1,2)--- (1,8)------ >>> mapped *~ 2 $ Just 24--- Just 48------ @--- ('*~') :: 'Num' b => 'Control.Lens.Type.Simple' 'Setter' a b -> b -> a -> a--- ('*~') :: 'Num' b => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b -> b -> a -> a--- ('*~') :: 'Num' b => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b -> b -> a -> a--- ('*~') :: 'Num' b => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> b -> a -> a--- @-(*~) :: Num c => Setting a b c c -> c -> a -> b-l *~ n = over l (* n)-{-# INLINE (*~) #-}---- | Decrement the target(s) of a numerically valued 'Control.Lens.Type.Lens', 'Control.Lens.Iso.Iso', 'Setter' or 'Control.Lens.Traversal.Traversal'------ >>> _1 -~ 2 $ (1,2)--- (-1,2)------ >>> mapped.mapped -~ 1 $ [[4,5],[6,7]]--- [[3,4],[5,6]]------ @--- ('-~') :: 'Num' b => 'Control.Lens.Type.Simple' 'Setter' a b -> b -> a -> a--- ('-~') :: 'Num' b => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b -> b -> a -> a--- ('-~') :: 'Num' b => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b -> b -> a -> a--- ('-~') :: 'Num' b => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> b -> a -> a--- @-(-~) :: Num c => Setting a b c c -> c -> a -> b-l -~ n = over l (subtract n)-{-# INLINE (-~) #-}---- | Divide the target(s) of a numerically valued 'Control.Lens.Type.Lens', 'Control.Lens.Iso.Iso', 'Setter' or 'Control.Lens.Traversal.Traversal'------ >>> _2 //~ 2 $ ("Hawaii",10)--- ("Hawaii",5.0)------ @--- ('//~') :: 'Fractional' b => 'Control.Lens.Type.Simple' 'Setter' a b -> b -> a -> a--- ('//~') :: 'Fractional' b => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b -> b -> a -> a--- ('//~') :: 'Fractional' b => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b -> b -> a -> a--- ('//~') :: 'Fractional' b => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> b -> a -> a--- @-(//~) :: Fractional c => Setting a b c c -> c -> a -> b-l //~ n = over l (/ n)---- | Raise the target(s) of a numerically valued 'Control.Lens.Type.Lens', 'Setter' or 'Control.Lens.Traversal.Traversal' to a non-negative integral power------ >>> _2 ^~ 2 $ (1,3)--- (1,9)------ @--- ('^~') :: ('Num' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Setter' a b -> c -> a -> a--- ('^~') :: ('Num' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b -> c -> a -> a--- ('^~') :: ('Num' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b -> c -> a -> a--- ('^~') :: ('Num' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> c -> a -> a--- @-(^~) :: (Num c, Integral e) => Setting a b c c -> e -> a -> b-l ^~ n = over l (^ n)-{-# INLINE (^~) #-}---- | Raise the target(s) of a fractionally valued 'Control.Lens.Type.Lens', 'Setter' or 'Control.Lens.Traversal.Traversal' to an integral power------ >>> _2 ^^~ (-1) $ (1,2)--- (1,0.5)------ @--- ('^^~') :: ('Fractional' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Setter' a b -> c -> a -> a--- ('^^~') :: ('Fractional' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b -> c -> a -> a--- ('^^~') :: ('Fractional' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b -> c -> a -> a--- ('^^~') :: ('Fractional' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> c -> a -> a--- @----(^^~) :: (Fractional c, Integral e) => Setting a b c c -> e -> a -> b-l ^^~ n = over l (^^ n)-{-# INLINE (^^~) #-}---- | Raise the target(s) of a floating-point valued 'Control.Lens.Type.Lens', 'Setter' or 'Control.Lens.Traversal.Traversal' to an arbitrary power.------ >>> _2 **~ pi $ (1,3)--- (1,31.54428070019754)------ @--- ('**~') :: 'Floating' b => 'Control.Lens.Type.Simple' 'Setter' a b -> b -> a -> a--- ('**~') :: 'Floating' b => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b -> b -> a -> a--- ('**~') :: 'Floating' b => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b -> b -> a -> a--- ('**~') :: 'Floating' b => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> b -> a -> a--- @-(**~) :: Floating c => Setting a b c c -> c -> a -> b-l **~ n = over l (** n)-{-# INLINE (**~) #-}---- | Logically '||' the target(s) of a 'Bool'-valued 'Control.Lens.Type.Lens' or 'Setter'------ >>> both ||~ True $ (False,True)--- (True,True)------ >>> both ||~ False $ (False,True)--- (False,True)------ @--- ('||~') :: 'Control.Lens.Type.Simple' 'Setter' a 'Bool' -> 'Bool' -> a -> a--- ('||~') :: 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a 'Bool' -> 'Bool' -> a -> a--- ('||~') :: 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a 'Bool' -> 'Bool' -> a -> a--- ('||~') :: 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a 'Bool' -> 'Bool' -> a -> a--- @-(||~):: Setting a b Bool Bool -> Bool -> a -> b-l ||~ n = over l (|| n)-{-# INLINE (||~) #-}---- | Logically '&&' the target(s) of a 'Bool'-valued 'Control.Lens.Type.Lens' or 'Setter'------ >>> both &&~ True $ (False, True)--- (False,True)------ >>> both &&~ False $ (False, True)--- (False,False)------ @--- ('&&~') :: 'Control.Lens.Type.Simple' 'Setter' a 'Bool' -> 'Bool' -> a -> a--- ('&&~') :: 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a 'Bool' -> 'Bool' -> a -> a--- ('&&~') :: 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a 'Bool' -> 'Bool' -> a -> a--- ('&&~') :: 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a 'Bool' -> 'Bool' -> a -> a--- @-(&&~) :: Setting a b Bool Bool -> Bool -> a -> b-l &&~ n = over l (&& n)-{-# INLINE (&&~) #-}----------------------------------------------------------------------------------- Using Setters with State----------------------------------------------------------------------------------- | Replace the target of a 'Control.Lens.Type.Lens' or all of the targets of a 'Setter' or 'Control.Lens.Traversal.Traversal' in our monadic--- state with a new value, irrespective of the old.------ This is an alias for ('.=').------ @--- 'assign' :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b       -> b -> m ()--- 'assign' :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b      -> b -> m ()--- 'assign' :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> b -> m ()--- 'assign' :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Setter' a b    -> b -> m ()--- @-assign :: MonadState a m => Setting a a c d -> d -> m ()-assign l b = State.modify (set l b)-{-# INLINE assign #-}---- | Replace the target of a 'Control.Lens.Type.Lens' or all of the targets of a 'Setter' or 'Control.Lens.Traversal.Traversal' in our monadic--- state with a new value, irrespective of the old.------ This is an infix version of 'assign'.------ @--- ('.=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b       -> b -> m ()--- ('.=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b      -> b -> m ()--- ('.=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> b -> m ()--- ('.=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Setter' a b    -> b -> m ()--- @------ "It puts the state in the monad or it gets the hose again."-(.=) :: MonadState a m => Setting a a c d -> d -> m ()-l .= b = State.modify (l .~ b)-{-# INLINE (.=) #-}---- | Map over the target of a 'Control.Lens.Type.Lens' or all of the targets of a 'Setter' or 'Control.Lens.Traversal.Traversal' in our monadic state.------ @--- ('%=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b       -> (b -> b) -> m ()--- ('%=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b      -> (b -> b) -> m ()--- ('%=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> (b -> b) -> m ()--- ('%=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Setter' a b    -> (b -> b) -> m ()--- @-(%=) :: MonadState a m => Setting a a c d -> (c -> d) -> m ()-l %= f = State.modify (l %~ f)-{-# INLINE (%=) #-}---- | Modify the target(s) of a 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens', 'Control.Lens.Iso.Iso', 'Setter' or 'Control.Lens.Traversal.Traversal' by adding a value------ Example:------ @--- fresh :: MonadState Int m => m Int--- fresh = do---   'id' '+=' 1---   'use' 'id'--- @------ @--- ('+=') :: ('MonadState' a m, 'Num' b) => 'Control.Lens.Type.Simple' 'Setter' a b -> b -> m ()--- ('+=') :: ('MonadState' a m, 'Num' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b -> b -> m ()--- ('+=') :: ('MonadState' a m, 'Num' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b -> b -> m ()--- ('+=') :: ('MonadState' a m, 'Num' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> b -> m ()--- @-(+=) :: (MonadState a m, Num b) => SimpleSetting a b -> b -> m ()-l += b = State.modify (l +~ b)-{-# INLINE (+=) #-}---- | Modify the target(s) of a 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens', 'Control.Lens.Iso.Iso', 'Setter' or 'Control.Lens.Traversal.Traversal' by subtracting a value------ @--- ('-=') :: ('MonadState' a m, 'Num' b) => 'Control.Lens.Type.Simple' 'Setter' a b -> b -> m ()--- ('-=') :: ('MonadState' a m, 'Num' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b -> b -> m ()--- ('-=') :: ('MonadState' a m, 'Num' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b -> b -> m ()--- ('-=') :: ('MonadState' a m, 'Num' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> b -> m ()--- @-(-=) :: (MonadState a m, Num b) => SimpleSetting a b -> b -> m ()-l -= b = State.modify (l -~ b)-{-# INLINE (-=) #-}---- | Modify the target(s) of a 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens', 'Control.Lens.Iso.Iso', 'Setter' or 'Control.Lens.Traversal.Traversal' by multiplying by value.------ @--- ('*=') :: ('MonadState' a m, 'Num' b) => 'Control.Lens.Type.Simple' 'Setter' a b -> b -> m ()--- ('*=') :: ('MonadState' a m, 'Num' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b -> b -> m ()--- ('*=') :: ('MonadState' a m, 'Num' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b -> b -> m ()--- ('*=') :: ('MonadState' a m, 'Num' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> b -> m ()--- @-(*=) :: (MonadState a m, Num b) => SimpleSetting a b -> b -> m ()-l *= b = State.modify (l *~ b)-{-# INLINE (*=) #-}---- | Modify the target(s) of a 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens', 'Control.Lens.Iso.Iso', 'Setter' or 'Control.Lens.Traversal.Traversal' by dividing by a value.------ @--- ('//=') :: ('MonadState' a m, 'Fractional' b) => 'Control.Lens.Type.Simple' 'Setter' a b -> b -> m ()--- ('//=') :: ('MonadState' a m, 'Fractional' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b -> b -> m ()--- ('//=') :: ('MonadState' a m, 'Fractional' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b -> b -> m ()--- ('//=') :: ('MonadState' a m, 'Fractional' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> b -> m ()--- @-(//=) :: (MonadState a m, Fractional b) => SimpleSetting a b -> b -> m ()-l //= b = State.modify (l //~ b)-{-# INLINE (//=) #-}---- | Raise the target(s) of a numerically valued 'Control.Lens.Type.Lens', 'Setter' or 'Control.Lens.Traversal.Traversal' to a non-negative integral power.------ @--- ('^=') ::  ('MonadState' a m, 'Fractional' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Setter' a b -> c -> m ()--- ('^=') ::  ('MonadState' a m, 'Fractional' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b -> c -> m ()--- ('^=') ::  ('MonadState' a m, 'Fractional' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b -> c -> m ()--- ('^=') ::  ('MonadState' a m, 'Fractional' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> c -> m ()--- @-(^=) :: (MonadState a m, Fractional b, Integral c) => SimpleSetting a b -> c -> m ()-l ^= c = State.modify (l ^~ c)-{-# INLINE (^=) #-}---- | Raise the target(s) of a numerically valued 'Control.Lens.Type.Lens', 'Setter' or 'Control.Lens.Traversal.Traversal' to an integral power.------ @--- ('^^=') ::  ('MonadState' a m, 'Fractional' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Setter' a b -> c -> m ()--- ('^^=') ::  ('MonadState' a m, 'Fractional' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b -> c -> m ()--- ('^^=') ::  ('MonadState' a m, 'Fractional' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b -> c -> m ()--- ('^^=') ::  ('MonadState' a m, 'Fractional' b, 'Integral' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> c -> m ()--- @-(^^=) :: (MonadState a m, Fractional b, Integral c) => SimpleSetting a b -> c -> m ()-l ^^= c = State.modify (l ^^~ c)-{-# INLINE (^^=) #-}---- | Raise the target(s) of a numerically valued 'Control.Lens.Type.Lens', 'Setter' or 'Control.Lens.Traversal.Traversal' to an arbitrary power------ @--- ('**=') ::  ('MonadState' a m, 'Floating' b) => 'Control.Lens.Type.Simple' 'Setter' a b -> b -> m ()--- ('**=') ::  ('MonadState' a m, 'Floating' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a b -> b -> m ()--- ('**=') ::  ('MonadState' a m, 'Floating' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a b -> b -> m ()--- ('**=') ::  ('MonadState' a m, 'Floating' b) => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a b -> b -> m ()--- @-(**=) :: (MonadState a m, Floating b) => SimpleSetting a b -> b -> m ()-l **= b = State.modify (l **~ b)-{-# INLINE (**=) #-}---- | Modify the target(s) of a 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens', 'Control.Lens.Iso.Iso', 'Setter' or 'Control.Lens.Traversal.Traversal' by taking their logical '&&' with a value------ @--- ('&&=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Setter' a 'Bool' -> 'Bool' -> m ()--- ('&&=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a 'Bool' -> 'Bool' -> m ()--- ('&&=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a 'Bool' -> 'Bool' -> m ()--- ('&&=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a 'Bool' -> 'Bool' -> m ()--- @-(&&=):: MonadState a m => SimpleSetting a Bool -> Bool -> m ()-l &&= b = State.modify (l &&~ b)-{-# INLINE (&&=) #-}---- | Modify the target(s) of a 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens', 'Iso, 'Setter' or 'Control.Lens.Traversal.Traversal' by taking their logical '||' with a value------ @--- ('||=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Setter' a 'Bool' -> 'Bool' -> m ()--- ('||=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a 'Bool' -> 'Bool' -> m ()--- ('||=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a 'Bool' -> 'Bool' -> m ()--- ('||=') :: 'MonadState' a m => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a 'Bool' -> 'Bool' -> m ()--- @-(||=) :: MonadState a m => SimpleSetting a Bool -> Bool -> m ()-l ||= b = State.modify (l ||~ b)-{-# INLINE (||=) #-}---- | Run a monadic action, and set all of the targets of a 'Control.Lens.Type.Lens', 'Setter' or 'Control.Lens.Traversal.Traversal' to its result.------ @--- ('<~') :: 'MonadState' a m => 'Control.Lens.Iso.Iso' a a c d       -> m d -> m ()--- ('<~') :: 'MonadState' a m => 'Control.Lens.Type.Lens' a a c d      -> m d -> m ()--- ('<~') :: 'MonadState' a m => 'Control.Lens.Traversal.Traversal' a a c d -> m d -> m ()--- ('<~') :: 'MonadState' a m => 'Setter' a a c d    -> m d -> m ()--- @------ As a reasonable mnemonic, this lets you store the result of a monadic action in a lens rather than--- in a local variable.------ @--- do foo <- bar---    ...--- @------ will store the result in a variable, while------ @--- do foo '<~' bar---    ...--- @------ will store the result in a 'Control.Lens.Type.Lens', 'Setter', or 'Control.Lens.Traversal.Traversal'.-(<~) :: MonadState a m => Setting a a c d -> m d -> m ()-l <~ md = md >>= (l .=)-{-# INLINE (<~) #-}---- | Set with pass-through------ This is useful for chaining assignment without round-tripping through your monad stack.------ @do x <- '_2' <.= ninety_nine_bottles_of_beer_on_the_wall@------ If you do not need a copy of the intermediate result, then using @l .= d@ will avoid unused binding warnings------ @--- ('<.=') :: 'MonadState' a m => 'Setter' a a c d -> d -> m d--- ('<.=') :: 'MonadState' a m => 'Control.Lens.Iso.Iso' a a c d -> d -> m d--- ('<.=') :: 'MonadState' a m => 'Control.Lens.Type.Lens' a a c d -> d -> m d--- ('<.=') :: 'MonadState' a m => 'Control.Lens.Traversal.Traversal' a a c d -> d -> m d--- @-(<.=) :: MonadState a m => Setting a a c d -> d -> m d-l <.= d = do-  l .= d-  return d-{-# INLINE (<.=) #-}---- | Reify a setter so it can be stored safely in a container.-newtype ReifiedSetter a b c d = ReifySetter { reflectSetter :: Setter a b c d }---- | @type 'SimpleReifiedSetter' = 'Control.Lens.Type.Simple' 'ReifiedSetter'@-type SimpleReifiedSetter a b = ReifiedSetter a a b b-+{-# LANGUAGE CPP #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE Trustworthy #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Setter+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  Rank2Types+--+-- A @'Setter' s t a b@ is a generalization of 'fmap' from 'Functor'. It allows you to map into a+-- structure and change out the contents, but it isn't strong enough to allow you to+-- enumerate those contents. Starting with @'fmap' :: 'Functor' f => (a -> b) -> f a -> f b@+-- we monomorphize the type to obtain @(a -> b) -> s -> t@ and then decorate it with 'Data.Functor.Identity.Identity' to obtain:+--+-- @+-- type 'Setter' s t a b = (a -> 'Data.Functor.Identity.Identity' b) -> s -> 'Data.Functor.Identity.Identity' t+-- @+--+-- Every 'Traversal' is a valid 'Setter', since 'Data.Functor.Identity.Identity' is 'Applicative'.+--+-- Everything you can do with a 'Functor', you can do with a 'Setter'. There+-- are combinators that generalize 'fmap' and ('<$').+----------------------------------------------------------------------------+module Control.Lens.Setter+  (+  -- * Setters+    Setter, Setter'+  , IndexedSetter, IndexedSetter'+  , ASetter, ASetter'+  , AnIndexedSetter, AnIndexedSetter'+  , Setting, Setting'+  -- * Building Setters+  , sets, setting+  , cloneSetter+  , cloneIndexPreservingSetter+  , cloneIndexedSetter+  -- * Common Setters+  , mapped, lifted+  , contramapped+  , argument+  -- * Functional Combinators+  , over+  , set+  , (.~), (%~)+  , (+~), (-~), (*~), (//~), (^~), (^^~), (**~), (||~), (<>~), (<>:~), (&&~), (<.~), (?~), (<?~)+  -- * State Combinators+  , assign, modifying+  , (.=), (%=)+  , (+=), (-=), (*=), (//=), (^=), (^^=), (**=), (||=), (<>=), (<>:=), (&&=), (<.=), (?=), (<?=)+  , (<~)+  -- * Writer Combinators+  , scribe+  , passing, ipassing+  , censoring, icensoring+  -- * Reader Combinators+  , locally, ilocally+  -- * Simplified State Setting+  , set'+  -- * Indexed Setters+  , imapOf, iover, iset, imodifying+  , isets+  , (%@~), (.@~), (%@=), (.@=)+  -- * Arrow operators+  , assignA+  -- * Exported for legible error messages+  , Settable+  , Identity(..)+  -- * Deprecated+  , mapOf+  ) where++import Prelude ()++import Control.Arrow+import Control.Comonad+import Control.Lens.Internal.Indexed+import Control.Lens.Internal.Prelude+import Control.Lens.Internal.Setter+import Control.Lens.Type+import Control.Monad (liftM)+import Control.Monad.Reader.Class as Reader+import Control.Monad.State.Class  as State+import Control.Monad.Writer.Class as Writer++-- $setup+-- >>> import Control.Lens+-- >>> import Control.Monad.State+-- >>> import Data.Char+-- >>> import Data.Functor.Contravariant (Predicate (..), Op (..))+-- >>> import qualified Data.Map as Map+-- >>> import Data.Semigroup (Sum (..), Product (..), Semigroup (..))+-- >>> import Debug.SimpleReflect.Expr as Expr+-- >>> import Debug.SimpleReflect.Vars as Vars+-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f+-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g+-- >>> let h :: Expr -> Expr -> Expr; h = Debug.SimpleReflect.Vars.h+-- >>> let getter :: Expr -> Expr; getter = fun "getter"+-- >>> let setter :: Expr -> Expr -> Expr; setter = fun "setter"+-- >>> :set -XNoOverloadedStrings++infixr 4 %@~, .@~, .~, +~, *~, -~, //~, ^~, ^^~, **~, &&~, <>~, <>:~, ||~, %~, <.~, ?~, <?~+infix  4 %@=, .@=, .=, +=, *=, -=, //=, ^=, ^^=, **=, &&=, <>=, <>:=, ||=, %=, <.=, ?=, <?=+infixr 2 <~++------------------------------------------------------------------------------+-- Setters+------------------------------------------------------------------------------++-- | Running a 'Setter' instantiates it to a concrete type.+--+-- When consuming a setter directly to perform a mapping, you can use this type, but most+-- user code will not need to use this type.+type ASetter s t a b = (a -> Identity b) -> s -> Identity t++-- | This is a useful alias for use when consuming a 'Setter''.+--+-- Most user code will never have to use this type.+--+-- @+-- type 'ASetter'' = 'Simple' 'ASetter'+-- @+type ASetter' s a = ASetter s s a a++-- | Running an 'IndexedSetter' instantiates it to a concrete type.+--+-- When consuming a setter directly to perform a mapping, you can use this type, but most+-- user code will not need to use this type.+type AnIndexedSetter i s t a b = Indexed i a (Identity b) -> s -> Identity t++-- | @+-- type 'AnIndexedSetter'' i = 'Simple' ('AnIndexedSetter' i)+-- @+type AnIndexedSetter' i s a = AnIndexedSetter i s s a a++-- | This is a convenient alias when defining highly polymorphic code that takes both+-- 'ASetter' and 'AnIndexedSetter' as appropriate. If a function takes this it is+-- expecting one of those two things based on context.+type Setting p s t a b = p a (Identity b) -> s -> Identity t++-- | This is a convenient alias when defining highly polymorphic code that takes both+-- 'ASetter'' and 'AnIndexedSetter'' as appropriate. If a function takes this it is+-- expecting one of those two things based on context.+type Setting' p s a = Setting p s s a a++-----------------------------------------------------------------------------+-- Setters+-----------------------------------------------------------------------------++-- | This 'Setter' can be used to map over all of the values in a 'Functor'.+--+-- @+-- 'fmap' ≡ 'over' 'mapped'+-- 'Data.Traversable.fmapDefault' ≡ 'over' 'Data.Traversable.traverse'+-- ('<$') ≡ 'set' 'mapped'+-- @+--+-- >>> over mapped f [a,b,c]+-- [f a,f b,f c]+--+-- >>> over mapped (+1) [1,2,3]+-- [2,3,4]+--+-- >>> set mapped x [a,b,c]+-- [x,x,x]+--+-- >>> [[a,b],[c]] & mapped.mapped +~ x+-- [[a + x,b + x],[c + x]]+--+-- >>> over (mapped._2) length [("hello","world"),("leaders","!!!")]+-- [("hello",5),("leaders",3)]+--+-- @+-- 'mapped' :: 'Functor' f => 'Setter' (f a) (f b) a b+-- @+--+-- If you want an 'IndexPreservingSetter' use @'setting' 'fmap'@.+mapped :: Functor f => Setter (f a) (f b) a b+mapped = sets fmap+{-# INLINE mapped #-}++-- | This 'setter' can be used to modify all of the values in a 'Monad'.+--+-- You sometimes have to use this rather than 'mapped' -- due to+-- temporary insanity 'Functor' was not a superclass of 'Monad' until+-- GHC 7.10.+--+-- @+-- 'liftM' ≡ 'over' 'lifted'+-- @+--+-- >>> over lifted f [a,b,c]+-- [f a,f b,f c]+--+-- >>> set lifted b (Just a)+-- Just b+--+-- If you want an 'IndexPreservingSetter' use @'setting' 'liftM'@.+lifted :: Monad m => Setter (m a) (m b) a b+lifted = sets liftM+{-# INLINE lifted #-}++-- | This 'Setter' can be used to map over all of the inputs to a 'Contravariant'.+--+-- @+-- 'contramap' ≡ 'over' 'contramapped'+-- @+--+-- >>> getPredicate (over contramapped (*2) (Predicate even)) 5+-- True+--+-- >>> getOp (over contramapped (*5) (Op show)) 100+-- "500"+--+-- >>> Prelude.map ($ 1) $ over (mapped . _Unwrapping' Op . contramapped) (*12) [(*2),(+1),(^3)]+-- [24,13,1728]+--+contramapped :: Contravariant f => Setter (f b) (f a) a b+contramapped = sets contramap+{-# INLINE contramapped #-}++-- | This 'Setter' can be used to map over the input of a 'Profunctor'.+--+-- The most common 'Profunctor' to use this with is @(->)@.+--+-- >>> (argument %~ f) g x+-- g (f x)+--+-- >>> (argument %~ show) length [1,2,3]+-- 7+--+-- >>> (argument %~ f) h x y+-- h (f x) y+--+-- Map over the argument of the result of a function -- i.e., its second+-- argument:+--+-- >>> (mapped.argument %~ f) h x y+-- h x (f y)+--+-- @+-- 'argument' :: 'Setter' (b -> r) (a -> r) a b+-- @+argument :: Profunctor p => Setter (p b r) (p a r) a b+argument = sets lmap+{-# INLINE argument #-}++-- | Build an index-preserving 'Setter' from a map-like function.+--+-- Your supplied function @f@ is required to satisfy:+--+-- @+-- f 'id' ≡ 'id'+-- f g '.' f h ≡ f (g '.' h)+-- @+--+-- Equational reasoning:+--+-- @+-- 'setting' '.' 'over' ≡ 'id'+-- 'over' '.' 'setting' ≡ 'id'+-- @+--+-- Another way to view 'sets' is that it takes a \"semantic editor combinator\"+-- and transforms it into a 'Setter'.+--+-- @+-- 'setting' :: ((a -> b) -> s -> t) -> 'Setter' s t a b+-- @+setting :: ((a -> b) -> s -> t) -> IndexPreservingSetter s t a b+setting l pafb = cotabulate $ \ws -> pure $ l (\a -> untainted (cosieve pafb (a <$ ws))) (extract ws)+{-# INLINE setting #-}++-- | Build a 'Setter', 'IndexedSetter' or 'IndexPreservingSetter' depending on your choice of 'Profunctor'.+--+-- @+-- 'sets' :: ((a -> b) -> s -> t) -> 'Setter' s t a b+-- @+sets :: (Profunctor p, Profunctor q, Settable f) => (p a b -> q s t) -> Optical p q f s t a b+sets f g = taintedDot (f (untaintedDot g))+{-# INLINE sets #-}++-- | Restore 'ASetter' to a full 'Setter'.+cloneSetter :: ASetter s t a b -> Setter s t a b+cloneSetter l afb = taintedDot $ coerce l (untaintedDot afb)+{-# INLINE cloneSetter #-}++-- | Build an 'IndexPreservingSetter' from any 'Setter'.+cloneIndexPreservingSetter :: ASetter s t a b -> IndexPreservingSetter s t a b+cloneIndexPreservingSetter l pafb = cotabulate $ \ws ->+    taintedDot runIdentity $ l (\a -> Identity (untainted (cosieve pafb (a <$ ws)))) (extract ws)+{-# INLINE cloneIndexPreservingSetter #-}++-- | Clone an 'IndexedSetter'.+cloneIndexedSetter :: AnIndexedSetter i s t a b -> IndexedSetter i s t a b+cloneIndexedSetter l pafb = taintedDot (runIdentity #. l (Indexed $ \i -> Identity #. untaintedDot (indexed pafb i)))+{-# INLINE cloneIndexedSetter #-}++-----------------------------------------------------------------------------+-- Using Setters+-----------------------------------------------------------------------------++-- | Modify the target of a 'Lens' or all the targets of a 'Setter' or 'Traversal'+-- with a function.+--+-- @+-- 'fmap' ≡ 'over' 'mapped'+-- 'Data.Traversable.fmapDefault' ≡ 'over' 'Data.Traversable.traverse'+-- 'sets' '.' 'over' ≡ 'id'+-- 'over' '.' 'sets' ≡ 'id'+-- @+--+-- Given any valid 'Setter' @l@, you can also rely on the law:+--+-- @+-- 'over' l f '.' 'over' l g = 'over' l (f '.' g)+-- @+--+-- /e.g./+--+-- >>> over mapped f (over mapped g [a,b,c]) == over mapped (f . g) [a,b,c]+-- True+--+-- Another way to view 'over' is to say that it transforms a 'Setter' into a+-- \"semantic editor combinator\".+--+-- >>> over mapped f (Just a)+-- Just (f a)+--+-- >>> over mapped (*10) [1,2,3]+-- [10,20,30]+--+-- >>> over _1 f (a,b)+-- (f a,b)+--+-- >>> over _1 show (10,20)+-- ("10",20)+--+-- @+-- 'over' :: 'Setter' s t a b -> (a -> b) -> s -> t+-- 'over' :: 'ASetter' s t a b -> (a -> b) -> s -> t+-- @+over :: ASetter s t a b -> (a -> b) -> s -> t+over = coerce+{-# INLINE over #-}++-- | Replace the target of a 'Lens' or all of the targets of a 'Setter'+-- or 'Traversal' with a constant value.+--+-- @+-- ('<$') ≡ 'set' 'mapped'+-- @+--+-- >>> set _2 "hello" (1,())+-- (1,"hello")+--+-- >>> set mapped () [1,2,3,4]+-- [(),(),(),()]+--+-- Note: Attempting to 'set' a 'Fold' or 'Getter' will fail at compile time with an+-- relatively nice error message.+--+-- @+-- 'set' :: 'Setter' s t a b    -> b -> s -> t+-- 'set' :: 'Iso' s t a b       -> b -> s -> t+-- 'set' :: 'Lens' s t a b      -> b -> s -> t+-- 'set' :: 'Traversal' s t a b -> b -> s -> t+-- @+set :: ASetter s t a b -> b -> s -> t+set l b = runIdentity #. l (\_ -> Identity b)+{-# INLINE set #-}++-- | Replace the target of a 'Lens' or all of the targets of a 'Setter''+-- or 'Traversal' with a constant value, without changing its type.+--+-- This is a type restricted version of 'set', which retains the type of the original.+--+-- >>> set' mapped x [a,b,c,d]+-- [x,x,x,x]+--+-- >>> set' _2 "hello" (1,"world")+-- (1,"hello")+--+-- >>> set' mapped 0 [1,2,3,4]+-- [0,0,0,0]+--+-- Note: Attempting to adjust 'set'' a 'Fold' or 'Getter' will fail at compile time with an+-- relatively nice error message.+--+-- @+-- 'set'' :: 'Setter'' s a    -> a -> s -> s+-- 'set'' :: 'Iso'' s a       -> a -> s -> s+-- 'set'' :: 'Lens'' s a      -> a -> s -> s+-- 'set'' :: 'Traversal'' s a -> a -> s -> s+-- @+set' :: ASetter' s a -> a -> s -> s+set' l b = runIdentity #. l (\_ -> Identity b)+{-# INLINE set' #-}++-- | Modifies the target of a 'Lens' or all of the targets of a 'Setter' or+-- 'Traversal' with a user supplied function.+--+-- This is an infix version of 'over'.+--+-- @+-- 'fmap' f ≡ 'mapped' '%~' f+-- 'Data.Traversable.fmapDefault' f ≡ 'Data.Traversable.traverse' '%~' f+-- @+--+-- >>> (a,b,c) & _3 %~ f+-- (a,b,f c)+--+-- >>> (a,b) & both %~ f+-- (f a,f b)+--+-- >>> _2 %~ length $ (1,"hello")+-- (1,5)+--+-- >>> traverse %~ f $ [a,b,c]+-- [f a,f b,f c]+--+-- >>> traverse %~ even $ [1,2,3]+-- [False,True,False]+--+-- >>> traverse.traverse %~ length $ [["hello","world"],["!!!"]]+-- [[5,5],[3]]+--+-- @+-- ('%~') :: 'Setter' s t a b    -> (a -> b) -> s -> t+-- ('%~') :: 'Iso' s t a b       -> (a -> b) -> s -> t+-- ('%~') :: 'Lens' s t a b      -> (a -> b) -> s -> t+-- ('%~') :: 'Traversal' s t a b -> (a -> b) -> s -> t+-- @+(%~) :: ASetter s t a b -> (a -> b) -> s -> t+(%~) = over+{-# INLINE (%~) #-}++-- | Replace the target of a 'Lens' or all of the targets of a 'Setter'+-- or 'Traversal' with a constant value.+--+-- This is an infix version of 'set', provided for consistency with ('.=').+--+-- @+-- f '<$' a ≡ 'mapped' '.~' f '$' a+-- @+--+-- >>> (a,b,c,d) & _4 .~ e+-- (a,b,c,e)+--+-- >>> (42,"world") & _1 .~ "hello"+-- ("hello","world")+--+-- >>> (a,b) & both .~ c+-- (c,c)+--+-- @+-- ('.~') :: 'Setter' s t a b    -> b -> s -> t+-- ('.~') :: 'Iso' s t a b       -> b -> s -> t+-- ('.~') :: 'Lens' s t a b      -> b -> s -> t+-- ('.~') :: 'Traversal' s t a b -> b -> s -> t+-- @+(.~) :: ASetter s t a b -> b -> s -> t+(.~) = set+{-# INLINE (.~) #-}++-- | Set the target of a 'Lens', 'Traversal' or 'Setter' to 'Just' a value.+--+-- @+-- l '?~' t ≡ 'set' l ('Just' t)+-- @+--+-- >>> Nothing & id ?~ a+-- Just a+--+-- >>> Map.empty & at 3 ?~ x+-- fromList [(3,x)]+--+-- '?~' can be used type-changily:+--+-- >>> ('a', ('b', 'c')) & _2.both ?~ 'x'+-- ('a',(Just 'x',Just 'x'))+--+-- @+-- ('?~') :: 'Setter' s t a ('Maybe' b)    -> b -> s -> t+-- ('?~') :: 'Iso' s t a ('Maybe' b)       -> b -> s -> t+-- ('?~') :: 'Lens' s t a ('Maybe' b)      -> b -> s -> t+-- ('?~') :: 'Traversal' s t a ('Maybe' b) -> b -> s -> t+-- @+(?~) :: ASetter s t a (Maybe b) -> b -> s -> t+l ?~ b = set l (Just b)+{-# INLINE (?~) #-}++-- | Set with pass-through.+--+-- This is mostly present for consistency, but may be useful for chaining assignments.+--+-- If you do not need a copy of the intermediate result, then using @l '.~' t@ directly is a good idea.+--+-- >>> (a,b) & _1 <.~ c+-- (c,(c,b))+--+-- >>> ("good","morning","vietnam") & _3 <.~ "world"+-- ("world",("good","morning","world"))+--+-- >>> (42,Map.fromList [("goodnight","gracie")]) & _2.at "hello" <.~ Just "world"+-- (Just "world",(42,fromList [("goodnight","gracie"),("hello","world")]))+--+-- @+-- ('<.~') :: 'Setter' s t a b    -> b -> s -> (b, t)+-- ('<.~') :: 'Iso' s t a b       -> b -> s -> (b, t)+-- ('<.~') :: 'Lens' s t a b      -> b -> s -> (b, t)+-- ('<.~') :: 'Traversal' s t a b -> b -> s -> (b, t)+-- @+(<.~) :: ASetter s t a b -> b -> s -> (b, t)+l <.~ b = \s -> (b, set l b s)+{-# INLINE (<.~) #-}++-- | Set to 'Just' a value with pass-through.+--+-- This is mostly present for consistency, but may be useful for for chaining assignments.+--+-- If you do not need a copy of the intermediate result, then using @l '?~' d@ directly is a good idea.+--+-- >>> import qualified Data.Map as Map+-- >>> _2.at "hello" <?~ "world" $ (42,Map.fromList [("goodnight","gracie")])+-- ("world",(42,fromList [("goodnight","gracie"),("hello","world")]))+--+-- @+-- ('<?~') :: 'Setter' s t a ('Maybe' b)    -> b -> s -> (b, t)+-- ('<?~') :: 'Iso' s t a ('Maybe' b)       -> b -> s -> (b, t)+-- ('<?~') :: 'Lens' s t a ('Maybe' b)      -> b -> s -> (b, t)+-- ('<?~') :: 'Traversal' s t a ('Maybe' b) -> b -> s -> (b, t)+-- @+(<?~) :: ASetter s t a (Maybe b) -> b -> s -> (b, t)+l <?~ b = \s -> (b, set l (Just b) s)+{-# INLINE (<?~) #-}++-- | Increment the target(s) of a numerically valued 'Lens', 'Setter' or 'Traversal'.+--+-- >>> (a,b) & _1 +~ c+-- (a + c,b)+--+-- >>> (a,b) & both +~ c+-- (a + c,b + c)+--+-- >>> (1,2) & _2 +~ 1+-- (1,3)+--+-- >>> [(a,b),(c,d)] & traverse.both +~ e+-- [(a + e,b + e),(c + e,d + e)]+--+-- @+-- ('+~') :: 'Num' a => 'Setter'' s a    -> a -> s -> s+-- ('+~') :: 'Num' a => 'Iso'' s a       -> a -> s -> s+-- ('+~') :: 'Num' a => 'Lens'' s a      -> a -> s -> s+-- ('+~') :: 'Num' a => 'Traversal'' s a -> a -> s -> s+-- @+(+~) :: Num a => ASetter s t a a -> a -> s -> t+l +~ n = over l (+ n)+{-# INLINE (+~) #-}++-- | Multiply the target(s) of a numerically valued 'Lens', 'Iso', 'Setter' or 'Traversal'.+--+-- >>> (a,b) & _1 *~ c+-- (a * c,b)+--+-- >>> (a,b) & both *~ c+-- (a * c,b * c)+--+-- >>> (1,2) & _2 *~ 4+-- (1,8)+--+-- >>> Just 24 & mapped *~ 2+-- Just 48+--+-- @+-- ('*~') :: 'Num' a => 'Setter'' s a    -> a -> s -> s+-- ('*~') :: 'Num' a => 'Iso'' s a       -> a -> s -> s+-- ('*~') :: 'Num' a => 'Lens'' s a      -> a -> s -> s+-- ('*~') :: 'Num' a => 'Traversal'' s a -> a -> s -> s+-- @+(*~) :: Num a => ASetter s t a a -> a -> s -> t+l *~ n = over l (* n)+{-# INLINE (*~) #-}++-- | Decrement the target(s) of a numerically valued 'Lens', 'Iso', 'Setter' or 'Traversal'.+--+-- >>> (a,b) & _1 -~ c+-- (a - c,b)+--+-- >>> (a,b) & both -~ c+-- (a - c,b - c)+--+-- >>> _1 -~ 2 $ (1,2)+-- (-1,2)+--+-- >>> mapped.mapped -~ 1 $ [[4,5],[6,7]]+-- [[3,4],[5,6]]+--+-- @+-- ('-~') :: 'Num' a => 'Setter'' s a    -> a -> s -> s+-- ('-~') :: 'Num' a => 'Iso'' s a       -> a -> s -> s+-- ('-~') :: 'Num' a => 'Lens'' s a      -> a -> s -> s+-- ('-~') :: 'Num' a => 'Traversal'' s a -> a -> s -> s+-- @+(-~) :: Num a => ASetter s t a a -> a -> s -> t+l -~ n = over l (subtract n)+{-# INLINE (-~) #-}++-- | Divide the target(s) of a numerically valued 'Lens', 'Iso', 'Setter' or 'Traversal'.+--+-- >>> (a,b) & _1 //~ c+-- (a / c,b)+--+-- >>> (a,b) & both //~ c+-- (a / c,b / c)+--+-- >>> ("Hawaii",10) & _2 //~ 2+-- ("Hawaii",5.0)+--+-- @+-- ('//~') :: 'Fractional' a => 'Setter'' s a    -> a -> s -> s+-- ('//~') :: 'Fractional' a => 'Iso'' s a       -> a -> s -> s+-- ('//~') :: 'Fractional' a => 'Lens'' s a      -> a -> s -> s+-- ('//~') :: 'Fractional' a => 'Traversal'' s a -> a -> s -> s+-- @+(//~) :: Fractional a => ASetter s t a a -> a -> s -> t+l //~ n = over l (/ n)+{-# INLINE (//~) #-}++-- | Raise the target(s) of a numerically valued 'Lens', 'Setter' or 'Traversal' to a non-negative integral power.+--+-- >>> (1,3) & _2 ^~ 2+-- (1,9)+--+-- @+-- ('^~') :: ('Num' a, 'Integral' e) => 'Setter'' s a    -> e -> s -> s+-- ('^~') :: ('Num' a, 'Integral' e) => 'Iso'' s a       -> e -> s -> s+-- ('^~') :: ('Num' a, 'Integral' e) => 'Lens'' s a      -> e -> s -> s+-- ('^~') :: ('Num' a, 'Integral' e) => 'Traversal'' s a -> e -> s -> s+-- @+(^~) :: (Num a, Integral e) => ASetter s t a a -> e -> s -> t+l ^~ n = over l (^ n)+{-# INLINE (^~) #-}++-- | Raise the target(s) of a fractionally valued 'Lens', 'Setter' or 'Traversal' to an integral power.+--+-- >>> (1,2) & _2 ^^~ (-1)+-- (1,0.5)+--+-- @+-- ('^^~') :: ('Fractional' a, 'Integral' e) => 'Setter'' s a    -> e -> s -> s+-- ('^^~') :: ('Fractional' a, 'Integral' e) => 'Iso'' s a       -> e -> s -> s+-- ('^^~') :: ('Fractional' a, 'Integral' e) => 'Lens'' s a      -> e -> s -> s+-- ('^^~') :: ('Fractional' a, 'Integral' e) => 'Traversal'' s a -> e -> s -> s+-- @+--+(^^~) :: (Fractional a, Integral e) => ASetter s t a a -> e -> s -> t+l ^^~ n = over l (^^ n)+{-# INLINE (^^~) #-}++-- | Raise the target(s) of a floating-point valued 'Lens', 'Setter' or 'Traversal' to an arbitrary power.+--+-- >>> (a,b) & _1 **~ c+-- (a**c,b)+--+-- >>> (a,b) & both **~ c+-- (a**c,b**c)+--+-- >>> _2 **~ 10 $ (3,2)+-- (3,1024.0)+--+-- @+-- ('**~') :: 'Floating' a => 'Setter'' s a    -> a -> s -> s+-- ('**~') :: 'Floating' a => 'Iso'' s a       -> a -> s -> s+-- ('**~') :: 'Floating' a => 'Lens'' s a      -> a -> s -> s+-- ('**~') :: 'Floating' a => 'Traversal'' s a -> a -> s -> s+-- @+(**~) :: Floating a => ASetter s t a a -> a -> s -> t+l **~ n = over l (** n)+{-# INLINE (**~) #-}++-- | Logically '||' the target(s) of a 'Bool'-valued 'Lens' or 'Setter'.+--+-- >>> both ||~ True $ (False,True)+-- (True,True)+--+-- >>> both ||~ False $ (False,True)+-- (False,True)+--+-- @+-- ('||~') :: 'Setter'' s 'Bool'    -> 'Bool' -> s -> s+-- ('||~') :: 'Iso'' s 'Bool'       -> 'Bool' -> s -> s+-- ('||~') :: 'Lens'' s 'Bool'      -> 'Bool' -> s -> s+-- ('||~') :: 'Traversal'' s 'Bool' -> 'Bool' -> s -> s+-- @+(||~):: ASetter s t Bool Bool -> Bool -> s -> t+l ||~ n = over l (|| n)+{-# INLINE (||~) #-}++-- | Logically '&&' the target(s) of a 'Bool'-valued 'Lens' or 'Setter'.+--+-- >>> both &&~ True $ (False, True)+-- (False,True)+--+-- >>> both &&~ False $ (False, True)+-- (False,False)+--+-- @+-- ('&&~') :: 'Setter'' s 'Bool'    -> 'Bool' -> s -> s+-- ('&&~') :: 'Iso'' s 'Bool'       -> 'Bool' -> s -> s+-- ('&&~') :: 'Lens'' s 'Bool'      -> 'Bool' -> s -> s+-- ('&&~') :: 'Traversal'' s 'Bool' -> 'Bool' -> s -> s+-- @+(&&~) :: ASetter s t Bool Bool -> Bool -> s -> t+l &&~ n = over l (&& n)+{-# INLINE (&&~) #-}++------------------------------------------------------------------------------+-- Using Setters with State+------------------------------------------------------------------------------++-- | Replace the target of a 'Lens' or all of the targets of a 'Setter' or 'Traversal' in our monadic+-- state with a new value, irrespective of the old.+--+-- This is an alias for ('.=').+--+-- >>> execState (do assign _1 c; assign _2 d) (a,b)+-- (c,d)+--+-- >>> execState (both .= c) (a,b)+-- (c,c)+--+-- @+-- 'assign' :: 'MonadState' s m => 'Iso'' s a       -> a -> m ()+-- 'assign' :: 'MonadState' s m => 'Lens'' s a      -> a -> m ()+-- 'assign' :: 'MonadState' s m => 'Traversal'' s a -> a -> m ()+-- 'assign' :: 'MonadState' s m => 'Setter'' s a    -> a -> m ()+-- @+assign :: MonadState s m => ASetter s s a b -> b -> m ()+assign l b = State.modify (set l b)+{-# INLINE assign #-}++-- | Replace the target of a 'Lens' or all of the targets of a 'Setter'+-- or 'Traversal' in our monadic state with a new value, irrespective of the+-- old.+--+-- This is an infix version of 'assign'.+--+-- >>> execState (do _1 .= c; _2 .= d) (a,b)+-- (c,d)+--+-- >>> execState (both .= c) (a,b)+-- (c,c)+--+-- @+-- ('.=') :: 'MonadState' s m => 'Iso'' s a       -> a -> m ()+-- ('.=') :: 'MonadState' s m => 'Lens'' s a      -> a -> m ()+-- ('.=') :: 'MonadState' s m => 'Traversal'' s a -> a -> m ()+-- ('.=') :: 'MonadState' s m => 'Setter'' s a    -> a -> m ()+-- @+--+-- /It puts the state in the monad or it gets the hose again./+(.=) :: MonadState s m => ASetter s s a b -> b -> m ()+l .= b = State.modify (l .~ b)+{-# INLINE (.=) #-}++-- | Map over the target of a 'Lens' or all of the targets of a 'Setter' or 'Traversal' in our monadic state.+--+-- >>> execState (do _1 %= f;_2 %= g) (a,b)+-- (f a,g b)+--+-- >>> execState (do both %= f) (a,b)+-- (f a,f b)+--+-- @+-- ('%=') :: 'MonadState' s m => 'Iso'' s a       -> (a -> a) -> m ()+-- ('%=') :: 'MonadState' s m => 'Lens'' s a      -> (a -> a) -> m ()+-- ('%=') :: 'MonadState' s m => 'Traversal'' s a -> (a -> a) -> m ()+-- ('%=') :: 'MonadState' s m => 'Setter'' s a    -> (a -> a) -> m ()+-- @+--+-- @+-- ('%=') :: 'MonadState' s m => 'ASetter' s s a b -> (a -> b) -> m ()+-- @+(%=) :: MonadState s m => ASetter s s a b -> (a -> b) -> m ()+l %= f = State.modify (l %~ f)+{-# INLINE (%=) #-}++-- | This is an alias for ('%=').+modifying :: MonadState s m => ASetter s s a b -> (a -> b) -> m ()+modifying l f = State.modify (over l f)+{-# INLINE modifying #-}++-- | Replace the target of a 'Lens' or all of the targets of a 'Setter' or 'Traversal' in our monadic+-- state with 'Just' a new value, irrespective of the old.+--+-- >>> execState (do at 1 ?= a; at 2 ?= b) Map.empty+-- fromList [(1,a),(2,b)]+--+-- >>> execState (do _1 ?= b; _2 ?= c) (Just a, Nothing)+-- (Just b,Just c)+--+-- @+-- ('?=') :: 'MonadState' s m => 'Iso'' s ('Maybe' a)       -> a -> m ()+-- ('?=') :: 'MonadState' s m => 'Lens'' s ('Maybe' a)      -> a -> m ()+-- ('?=') :: 'MonadState' s m => 'Traversal'' s ('Maybe' a) -> a -> m ()+-- ('?=') :: 'MonadState' s m => 'Setter'' s ('Maybe' a)    -> a -> m ()+-- @+(?=) :: MonadState s m => ASetter s s a (Maybe b) -> b -> m ()+l ?= b = State.modify (l ?~ b)+{-# INLINE (?=) #-}++-- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' by adding a value.+--+-- Example:+--+-- @+-- 'fresh' :: 'MonadState' 'Int' m => m 'Int'+-- 'fresh' = do+--   'id' '+=' 1+--   'Control.Lens.Getter.use' 'id'+-- @+--+-- >>> execState (do _1 += c; _2 += d) (a,b)+-- (a + c,b + d)+--+-- >>> execState (do _1.at 1.non 0 += 10) (Map.fromList [(2,100)],"hello")+-- (fromList [(1,10),(2,100)],"hello")+--+-- @+-- ('+=') :: ('MonadState' s m, 'Num' a) => 'Setter'' s a    -> a -> m ()+-- ('+=') :: ('MonadState' s m, 'Num' a) => 'Iso'' s a       -> a -> m ()+-- ('+=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a      -> a -> m ()+-- ('+=') :: ('MonadState' s m, 'Num' a) => 'Traversal'' s a -> a -> m ()+-- @+(+=) :: (MonadState s m, Num a) => ASetter' s a -> a -> m ()+l += b = State.modify (l +~ b)+{-# INLINE (+=) #-}++-- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' by subtracting a value.+--+-- >>> execState (do _1 -= c; _2 -= d) (a,b)+-- (a - c,b - d)+--+-- @+-- ('-=') :: ('MonadState' s m, 'Num' a) => 'Setter'' s a    -> a -> m ()+-- ('-=') :: ('MonadState' s m, 'Num' a) => 'Iso'' s a       -> a -> m ()+-- ('-=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a      -> a -> m ()+-- ('-=') :: ('MonadState' s m, 'Num' a) => 'Traversal'' s a -> a -> m ()+-- @+(-=) :: (MonadState s m, Num a) => ASetter' s a -> a -> m ()+l -= b = State.modify (l -~ b)+{-# INLINE (-=) #-}++-- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' by multiplying by value.+--+-- >>> execState (do _1 *= c; _2 *= d) (a,b)+-- (a * c,b * d)+--+-- @+-- ('*=') :: ('MonadState' s m, 'Num' a) => 'Setter'' s a    -> a -> m ()+-- ('*=') :: ('MonadState' s m, 'Num' a) => 'Iso'' s a       -> a -> m ()+-- ('*=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a      -> a -> m ()+-- ('*=') :: ('MonadState' s m, 'Num' a) => 'Traversal'' s a -> a -> m ()+-- @+(*=) :: (MonadState s m, Num a) => ASetter' s a -> a -> m ()+l *= b = State.modify (l *~ b)+{-# INLINE (*=) #-}++-- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' by dividing by a value.+--+-- >>> execState (do _1 //= c; _2 //= d) (a,b)+-- (a / c,b / d)+--+-- @+-- ('//=') :: ('MonadState' s m, 'Fractional' a) => 'Setter'' s a    -> a -> m ()+-- ('//=') :: ('MonadState' s m, 'Fractional' a) => 'Iso'' s a       -> a -> m ()+-- ('//=') :: ('MonadState' s m, 'Fractional' a) => 'Lens'' s a      -> a -> m ()+-- ('//=') :: ('MonadState' s m, 'Fractional' a) => 'Traversal'' s a -> a -> m ()+-- @+(//=) :: (MonadState s m, Fractional a) => ASetter' s a -> a -> m ()+l //= a = State.modify (l //~ a)+{-# INLINE (//=) #-}++-- | Raise the target(s) of a numerically valued 'Lens', 'Setter' or 'Traversal' to a non-negative integral power.+--+-- @+-- ('^=') ::  ('MonadState' s m, 'Num' a, 'Integral' e) => 'Setter'' s a    -> e -> m ()+-- ('^=') ::  ('MonadState' s m, 'Num' a, 'Integral' e) => 'Iso'' s a       -> e -> m ()+-- ('^=') ::  ('MonadState' s m, 'Num' a, 'Integral' e) => 'Lens'' s a      -> e -> m ()+-- ('^=') ::  ('MonadState' s m, 'Num' a, 'Integral' e) => 'Traversal'' s a -> e -> m ()+-- @+(^=) :: (MonadState s m, Num a, Integral e) => ASetter' s a -> e -> m ()+l ^= e = State.modify (l ^~ e)+{-# INLINE (^=) #-}++-- | Raise the target(s) of a numerically valued 'Lens', 'Setter' or 'Traversal' to an integral power.+--+-- @+-- ('^^=') ::  ('MonadState' s m, 'Fractional' a, 'Integral' e) => 'Setter'' s a    -> e -> m ()+-- ('^^=') ::  ('MonadState' s m, 'Fractional' a, 'Integral' e) => 'Iso'' s a       -> e -> m ()+-- ('^^=') ::  ('MonadState' s m, 'Fractional' a, 'Integral' e) => 'Lens'' s a      -> e -> m ()+-- ('^^=') ::  ('MonadState' s m, 'Fractional' a, 'Integral' e) => 'Traversal'' s a -> e -> m ()+-- @+(^^=) :: (MonadState s m, Fractional a, Integral e) => ASetter' s a -> e -> m ()+l ^^= e = State.modify (l ^^~ e)+{-# INLINE (^^=) #-}++-- | Raise the target(s) of a numerically valued 'Lens', 'Setter' or 'Traversal' to an arbitrary power+--+-- >>> execState (do _1 **= c; _2 **= d) (a,b)+-- (a**c,b**d)+--+-- @+-- ('**=') ::  ('MonadState' s m, 'Floating' a) => 'Setter'' s a    -> a -> m ()+-- ('**=') ::  ('MonadState' s m, 'Floating' a) => 'Iso'' s a       -> a -> m ()+-- ('**=') ::  ('MonadState' s m, 'Floating' a) => 'Lens'' s a      -> a -> m ()+-- ('**=') ::  ('MonadState' s m, 'Floating' a) => 'Traversal'' s a -> a -> m ()+-- @+(**=) :: (MonadState s m, Floating a) => ASetter' s a -> a -> m ()+l **= a = State.modify (l **~ a)+{-# INLINE (**=) #-}++-- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' by taking their logical '&&' with a value.+--+-- >>> execState (do _1 &&= True; _2 &&= False; _3 &&= True; _4 &&= False) (True,True,False,False)+-- (True,False,False,False)+--+-- @+-- ('&&=') :: 'MonadState' s m => 'Setter'' s 'Bool'    -> 'Bool' -> m ()+-- ('&&=') :: 'MonadState' s m => 'Iso'' s 'Bool'       -> 'Bool' -> m ()+-- ('&&=') :: 'MonadState' s m => 'Lens'' s 'Bool'      -> 'Bool' -> m ()+-- ('&&=') :: 'MonadState' s m => 'Traversal'' s 'Bool' -> 'Bool' -> m ()+-- @+(&&=):: MonadState s m => ASetter' s Bool -> Bool -> m ()+l &&= b = State.modify (l &&~ b)+{-# INLINE (&&=) #-}++-- | Modify the target(s) of a 'Lens'', 'Iso, 'Setter' or 'Traversal' by taking their logical '||' with a value.+--+-- >>> execState (do _1 ||= True; _2 ||= False; _3 ||= True; _4 ||= False) (True,True,False,False)+-- (True,True,True,False)+--+-- @+-- ('||=') :: 'MonadState' s m => 'Setter'' s 'Bool'    -> 'Bool' -> m ()+-- ('||=') :: 'MonadState' s m => 'Iso'' s 'Bool'       -> 'Bool' -> m ()+-- ('||=') :: 'MonadState' s m => 'Lens'' s 'Bool'      -> 'Bool' -> m ()+-- ('||=') :: 'MonadState' s m => 'Traversal'' s 'Bool' -> 'Bool' -> m ()+-- @+(||=) :: MonadState s m => ASetter' s Bool -> Bool -> m ()+l ||= b = State.modify (l ||~ b)+{-# INLINE (||=) #-}++-- | Run a monadic action, and set all of the targets of a 'Lens', 'Setter' or 'Traversal' to its result.+--+-- @+-- ('<~') :: 'MonadState' s m => 'Iso' s s a b       -> m b -> m ()+-- ('<~') :: 'MonadState' s m => 'Lens' s s a b      -> m b -> m ()+-- ('<~') :: 'MonadState' s m => 'Traversal' s s a b -> m b -> m ()+-- ('<~') :: 'MonadState' s m => 'Setter' s s a b    -> m b -> m ()+-- @+--+-- As a reasonable mnemonic, this lets you store the result of a monadic action in a 'Lens' rather than+-- in a local variable.+--+-- @+-- do foo <- bar+--    ...+-- @+--+-- will store the result in a variable, while+--+-- @+-- do foo '<~' bar+--    ...+-- @+--+-- will store the result in a 'Lens', 'Setter', or 'Traversal'.+(<~) :: MonadState s m => ASetter s s a b -> m b -> m ()+l <~ mb = mb >>= (l .=)+{-# INLINE (<~) #-}++-- | Set with pass-through+--+-- This is useful for chaining assignment without round-tripping through your 'Monad' stack.+--+-- @+-- do x <- 'Control.Lens.Tuple._2' '<.=' ninety_nine_bottles_of_beer_on_the_wall+-- @+--+-- If you do not need a copy of the intermediate result, then using @l '.=' d@ will avoid unused binding warnings.+--+-- @+-- ('<.=') :: 'MonadState' s m => 'Setter' s s a b    -> b -> m b+-- ('<.=') :: 'MonadState' s m => 'Iso' s s a b       -> b -> m b+-- ('<.=') :: 'MonadState' s m => 'Lens' s s a b      -> b -> m b+-- ('<.=') :: 'MonadState' s m => 'Traversal' s s a b -> b -> m b+-- @+(<.=) :: MonadState s m => ASetter s s a b -> b -> m b+l <.= b = do+  l .= b+  return b+{-# INLINE (<.=) #-}++-- | Set 'Just' a value with pass-through+--+-- This is useful for chaining assignment without round-tripping through your 'Monad' stack.+--+-- @+-- do x <- 'Control.Lens.At.at' "foo" '<?=' ninety_nine_bottles_of_beer_on_the_wall+-- @+--+-- If you do not need a copy of the intermediate result, then using @l '?=' d@ will avoid unused binding warnings.+--+-- @+-- ('<?=') :: 'MonadState' s m => 'Setter' s s a ('Maybe' b)    -> b -> m b+-- ('<?=') :: 'MonadState' s m => 'Iso' s s a ('Maybe' b)       -> b -> m b+-- ('<?=') :: 'MonadState' s m => 'Lens' s s a ('Maybe' b)      -> b -> m b+-- ('<?=') :: 'MonadState' s m => 'Traversal' s s a ('Maybe' b) -> b -> m b+-- @+(<?=) :: MonadState s m => ASetter s s a (Maybe b) -> b -> m b+l <?= b = do+  l ?= b+  return b+{-# INLINE (<?=) #-}++-- | Modify the target of a 'Semigroup' value by using @('<>')@.+--+-- >>> (Sum a,b) & _1 <>~ Sum c+-- (Sum {getSum = a + c},b)+--+-- >>> (Sum a,Sum b) & both <>~ Sum c+-- (Sum {getSum = a + c},Sum {getSum = b + c})+--+-- >>> both <>~ "!!!" $ ("hello","world")+-- ("hello!!!","world!!!")+--+-- @+-- ('<>~') :: 'Semigroup' a => 'Setter' s t a a    -> a -> s -> t+-- ('<>~') :: 'Semigroup' a => 'Iso' s t a a       -> a -> s -> t+-- ('<>~') :: 'Semigroup' a => 'Lens' s t a a      -> a -> s -> t+-- ('<>~') :: 'Semigroup' a => 'Traversal' s t a a -> a -> s -> t+-- @+(<>~) :: Semigroup a => ASetter s t a a -> a -> s -> t+l <>~ n = over l (<> n)+{-# INLINE (<>~) #-}++-- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' by using @('<>')@.+--+-- >>> execState (do _1 <>= Sum c; _2 <>= Product d) (Sum a,Product b)+-- (Sum {getSum = a + c},Product {getProduct = b * d})+--+-- >>> execState (both <>= "!!!") ("hello","world")+-- ("hello!!!","world!!!")+--+-- @+-- ('<>=') :: ('MonadState' s m, 'Semigroup' a) => 'Setter'' s a -> a -> m ()+-- ('<>=') :: ('MonadState' s m, 'Semigroup' a) => 'Iso'' s a -> a -> m ()+-- ('<>=') :: ('MonadState' s m, 'Semigroup' a) => 'Lens'' s a -> a -> m ()+-- ('<>=') :: ('MonadState' s m, 'Semigroup' a) => 'Traversal'' s a -> a -> m ()+-- @+(<>=) :: (MonadState s m, Semigroup a) => ASetter' s a -> a -> m ()+l <>= a = State.modify (l <>~ a)+{-# INLINE (<>=) #-}++-- | Modify the target of a 'Semigroup' value by using @('<>')@.+-- However, unlike '<>~', it is prepend to the head side.+--+-- >>> ["world"] & id <>:~ ["hello"]+-- ["hello","world"]+--+-- >>> (["world"], ["lens"]) & _1 <>:~ ["hello"]+-- (["hello","world"],["lens"])+(<>:~) :: Semigroup b => ASetter s t b b -> b -> s -> t+l <>:~ n = over l (n <>)+{-# INLINE (<>:~) #-}++-- | Modify the target(s) of a 'Lens'', 'Iso', 'Setter' or 'Traversal' by using @('<>')@.+-- However, unlike '<>=', it is prepend to the head side.+(<>:=) :: (MonadState s m, Semigroup a) => ASetter' s a -> a -> m ()+l <>:= a = State.modify (l <>:~ a)+{-# INLINE (<>:=) #-}++-----------------------------------------------------------------------------+-- Writer Operations+-----------------------------------------------------------------------------++-- | Write to a fragment of a larger 'Writer' format.+scribe :: (MonadWriter t m, Monoid s) => ASetter s t a b -> b -> m ()+scribe l b = tell (set l b mempty)+{-# INLINE scribe #-}++-- | This is a generalization of 'pass' that allows you to modify just a+-- portion of the resulting 'MonadWriter'.+passing :: MonadWriter w m => Setter w w u v -> m (a, u -> v) -> m a+passing l m = pass $ do+  (a, uv) <- m+  return (a, over l uv)+{-# INLINE passing #-}++-- | This is a generalization of 'pass' that allows you to modify just a+-- portion of the resulting 'MonadWriter' with access to the index of an+-- 'IndexedSetter'.+ipassing :: MonadWriter w m => IndexedSetter i w w u v -> m (a, i -> u -> v) -> m a+ipassing l m = pass $ do+  (a, uv) <- m+  return (a, iover l uv)+{-# INLINE ipassing #-}++-- | This is a generalization of 'censor' that allows you to 'censor' just a+-- portion of the resulting 'MonadWriter'.+censoring :: MonadWriter w m => Setter w w u v -> (u -> v) -> m a -> m a+censoring l uv = censor (over l uv)+{-# INLINE censoring #-}++-- | This is a generalization of 'censor' that allows you to 'censor' just a+-- portion of the resulting 'MonadWriter', with access to the index of an+-- 'IndexedSetter'.+icensoring :: MonadWriter w m => IndexedSetter i w w u v -> (i -> u -> v) -> m a -> m a+icensoring l uv = censor (iover l uv)+{-# INLINE icensoring #-}++-----------------------------------------------------------------------------+-- Reader Operations+-----------------------------------------------------------------------------++-- | Modify the value of the 'Reader' environment associated with the target of a+-- 'Setter', 'Lens', or 'Traversal'.+--+-- @+-- 'locally' l 'id' a ≡ a+-- 'locally' l f '.' locally l g ≡ 'locally' l (f '.' g)+-- @+--+-- >>> (1,1) & locally _1 (+1) (uncurry (+))+-- 3+--+-- >>> "," & locally ($) ("Hello" <>) (<> " world!")+-- "Hello, world!"+--+-- @+-- locally :: MonadReader s m => 'Iso' s s a b       -> (a -> b) -> m r -> m r+-- locally :: MonadReader s m => 'Lens' s s a b      -> (a -> b) -> m r -> m r+-- locally :: MonadReader s m => 'Traversal' s s a b -> (a -> b) -> m r -> m r+-- locally :: MonadReader s m => 'Setter' s s a b    -> (a -> b) -> m r -> m r+-- @+locally :: MonadReader s m => ASetter s s a b -> (a -> b) -> m r -> m r+locally l f = Reader.local (over l f)+{-# INLINE locally #-}++-- | This is a generalization of 'locally' that allows one to make indexed+-- 'local' changes to a 'Reader' environment associated with the target of a+-- 'Setter', 'Lens', or 'Traversal'.+--+-- @+-- 'locally' l f ≡ 'ilocally' l f . const+-- 'ilocally' l f ≡ 'locally' l f . 'Indexed'+-- @+--+-- @+-- ilocally :: MonadReader s m => 'IndexedLens' s s a b      -> (i -> a -> b) -> m r -> m r+-- ilocally :: MonadReader s m => 'IndexedTraversal' s s a b -> (i -> a -> b) -> m r -> m r+-- ilocally :: MonadReader s m => 'IndexedSetter' s s a b    -> (i -> a -> b) -> m r -> m r+-- @+ilocally :: MonadReader s m => AnIndexedSetter i s s a b -> (i -> a -> b) -> m r -> m r+ilocally l f = Reader.local (iover l f)+{-# INLINE ilocally #-}++-----------------------------------------------------------------------------+-- Indexed Setters+-----------------------------------------------------------------------------+++-- | Map with index. This is an alias for 'imapOf'.+--+-- When you do not need access to the index, then 'over' is more liberal in what it can accept.+--+-- @+-- 'over' l ≡ 'iover' l '.' 'const'+-- 'iover' l ≡ 'over' l '.' 'Indexed'+-- @+--+-- @+-- 'iover' :: 'IndexedSetter' i s t a b    -> (i -> a -> b) -> s -> t+-- 'iover' :: 'IndexedLens' i s t a b      -> (i -> a -> b) -> s -> t+-- 'iover' :: 'IndexedTraversal' i s t a b -> (i -> a -> b) -> s -> t+-- @+iover :: AnIndexedSetter i s t a b -> (i -> a -> b) -> s -> t+iover = coerce+{-# INLINE iover #-}++-- | Set with index. Equivalent to 'iover' with the current value ignored.+--+-- When you do not need access to the index, then 'set' is more liberal in what it can accept.+--+-- @+-- 'set' l ≡ 'iset' l '.' 'const'+-- @+--+-- @+-- 'iset' :: 'IndexedSetter' i s t a b    -> (i -> b) -> s -> t+-- 'iset' :: 'IndexedLens' i s t a b      -> (i -> b) -> s -> t+-- 'iset' :: 'IndexedTraversal' i s t a b -> (i -> b) -> s -> t+-- @+iset :: AnIndexedSetter i s t a b -> (i -> b) -> s -> t+iset l = iover l . (const .)+{-# INLINE iset #-}++-- | Build an 'IndexedSetter' from an 'Control.Lens.Indexed.imap'-like function.+--+-- Your supplied function @f@ is required to satisfy:+--+-- @+-- f 'id' ≡ 'id'+-- f g '.' f h ≡ f (g '.' h)+-- @+--+-- Equational reasoning:+--+-- @+-- 'isets' '.' 'iover' ≡ 'id'+-- 'iover' '.' 'isets' ≡ 'id'+-- @+--+-- Another way to view 'isets' is that it takes a \"semantic editor combinator\"+-- which has been modified to carry an index and transforms it into a 'IndexedSetter'.+isets :: ((i -> a -> b) -> s -> t) -> IndexedSetter i s t a b+isets f = sets (f . indexed)+{-# INLINE isets #-}++-- | Adjust every target of an 'IndexedSetter', 'IndexedLens' or 'IndexedTraversal'+-- with access to the index.+--+-- @+-- ('%@~') ≡ 'iover'+-- @+--+-- When you do not need access to the index then ('%~') is more liberal in what it can accept.+--+-- @+-- l '%~' f ≡ l '%@~' 'const' f+-- @+--+-- @+-- ('%@~') :: 'IndexedSetter' i s t a b    -> (i -> a -> b) -> s -> t+-- ('%@~') :: 'IndexedLens' i s t a b      -> (i -> a -> b) -> s -> t+-- ('%@~') :: 'IndexedTraversal' i s t a b -> (i -> a -> b) -> s -> t+-- @+(%@~) :: AnIndexedSetter i s t a b -> (i -> a -> b) -> s -> t+(%@~) = iover+{-# INLINE (%@~) #-}++-- | Replace every target of an 'IndexedSetter', 'IndexedLens' or 'IndexedTraversal'+-- with access to the index.+--+-- @+-- ('.@~') ≡ 'iset'+-- @+--+-- When you do not need access to the index then ('.~') is more liberal in what it can accept.+--+-- @+-- l '.~' b ≡ l '.@~' 'const' b+-- @+--+-- @+-- ('.@~') :: 'IndexedSetter' i s t a b    -> (i -> b) -> s -> t+-- ('.@~') :: 'IndexedLens' i s t a b      -> (i -> b) -> s -> t+-- ('.@~') :: 'IndexedTraversal' i s t a b -> (i -> b) -> s -> t+-- @+(.@~) :: AnIndexedSetter i s t a b -> (i -> b) -> s -> t+l .@~ f = runIdentity #. l (Identity #. Indexed (const . f))+{-# INLINE (.@~) #-}++-- | Adjust every target in the current state of an 'IndexedSetter', 'IndexedLens' or 'IndexedTraversal'+-- with access to the index.+--+-- When you do not need access to the index then ('%=') is more liberal in what it can accept.+--+-- @+-- l '%=' f ≡ l '%@=' 'const' f+-- @+--+-- @+-- ('%@=') :: 'MonadState' s m => 'IndexedSetter' i s s a b    -> (i -> a -> b) -> m ()+-- ('%@=') :: 'MonadState' s m => 'IndexedLens' i s s a b      -> (i -> a -> b) -> m ()+-- ('%@=') :: 'MonadState' s m => 'IndexedTraversal' i s t a b -> (i -> a -> b) -> m ()+-- @+(%@=) :: MonadState s m => AnIndexedSetter i s s a b -> (i -> a -> b) -> m ()+l %@= f = State.modify (l %@~ f)+{-# INLINE (%@=) #-}++-- | This is an alias for ('%@=').+imodifying :: MonadState s m => AnIndexedSetter i s s a b -> (i -> a -> b) -> m ()+imodifying l f = State.modify (iover l f)+{-# INLINE imodifying #-}++-- | Replace every target in the current state of an 'IndexedSetter', 'IndexedLens' or 'IndexedTraversal'+-- with access to the index.+--+-- When you do not need access to the index then ('.=') is more liberal in what it can accept.+--+-- @+-- l '.=' b ≡ l '.@=' 'const' b+-- @+--+-- @+-- ('.@=') :: 'MonadState' s m => 'IndexedSetter' i s s a b    -> (i -> b) -> m ()+-- ('.@=') :: 'MonadState' s m => 'IndexedLens' i s s a b      -> (i -> b) -> m ()+-- ('.@=') :: 'MonadState' s m => 'IndexedTraversal' i s t a b -> (i -> b) -> m ()+-- @+(.@=) :: MonadState s m => AnIndexedSetter i s s a b -> (i -> b) -> m ()+l .@= f = State.modify (l .@~ f)+{-# INLINE (.@=) #-}++------------------------------------------------------------------------------+-- Arrows+------------------------------------------------------------------------------++-- | Run an arrow command and use the output to set all the targets of+-- a 'Lens', 'Setter' or 'Traversal' to the result.+--+-- 'assignA' can be used very similarly to ('<~'), except that the type of+-- the object being modified can change; for example:+--+-- @+-- runKleisli action ((), (), ()) where+--   action =      assignA _1 (Kleisli (const getVal1))+--            \>>> assignA _2 (Kleisli (const getVal2))+--            \>>> assignA _3 (Kleisli (const getVal3))+--   getVal1 :: Either String Int+--   getVal1 = ...+--   getVal2 :: Either String Bool+--   getVal2 = ...+--   getVal3 :: Either String Char+--   getVal3 = ...+-- @+--+-- has the type @'Either' 'String' ('Int', 'Bool', 'Char')@+--+-- @+-- 'assignA' :: 'Arrow' p => 'Iso' s t a b       -> p s b -> p s t+-- 'assignA' :: 'Arrow' p => 'Lens' s t a b      -> p s b -> p s t+-- 'assignA' :: 'Arrow' p => 'Traversal' s t a b -> p s b -> p s t+-- 'assignA' :: 'Arrow' p => 'Setter' s t a b    -> p s b -> p s t+-- @+assignA :: Arrow p => ASetter s t a b -> p s b -> p s t+assignA l p = arr (flip $ set l) &&& p >>> arr (uncurry id)+{-# INLINE assignA #-}++------------------------------------------------------------------------------+-- Deprecated+------------------------------------------------------------------------------++-- | 'mapOf' is a deprecated alias for 'over'.+mapOf :: ASetter s t a b -> (a -> b) -> s -> t+mapOf = over+{-# INLINE mapOf #-}+{-# DEPRECATED mapOf "Use `over`" #-}++-- | Map with index. (Deprecated alias for 'iover').+--+-- When you do not need access to the index, then 'mapOf' is more liberal in what it can accept.+--+-- @+-- 'mapOf' l ≡ 'imapOf' l '.' 'const'+-- @+--+-- @+-- 'imapOf' :: 'IndexedSetter' i s t a b    -> (i -> a -> b) -> s -> t+-- 'imapOf' :: 'IndexedLens' i s t a b      -> (i -> a -> b) -> s -> t+-- 'imapOf' :: 'IndexedTraversal' i s t a b -> (i -> a -> b) -> s -> t+-- @+imapOf :: AnIndexedSetter i s t a b -> (i -> a -> b) -> s -> t+imapOf = iover+{-# INLINE imapOf #-}+{-# DEPRECATED imapOf "Use `iover`" #-}
src/Control/Lens/TH.hs view
@@ -1,583 +1,873 @@ {-# LANGUAGE CPP #-}-{-# LANGUAGE TemplateHaskell #-}-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 704-{-# LANGUAGE Trustworthy #-}-#endif---- in case we're being loaded from ghci-#ifndef MIN_VERSION_template_haskell-#define MIN_VERSION_template_haskell(x,y,z) (defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 706)-#endif--------------------------------------------------------------------------------- |--- Module      :  Control.Lens.TH--- Copyright   :  (C) 2012 Edward Kmett, Michael Sloan--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  experimental--- Portability :  TemplateHaskell----------------------------------------------------------------------------------module Control.Lens.TH-  (-  -- * Constructing Lenses Automatically-    makeLenses, makeLensesFor-  , makeClassy, makeClassyFor-  , makeIso-  -- * Configuring Lenses-  , makeLensesWith-  , defaultRules-  , LensRules(LensRules)-  , lensRules-  , classyRules-  , isoRules-  , lensIso-  , lensField-  , lensClass-  , lensFlags-  , LensFlag(..)-  , simpleLenses, partialLenses, buildTraversals, handleSingletons, singletonIso, singletonRequired, createClass, createInstance, classRequired, singletonAndField-  ) where--import Control.Applicative-import Control.Lens.Fold-import Control.Lens.Getter-import Control.Lens.Iso-import Control.Lens.Setter-import Control.Lens.Tuple-import Control.Lens.Traversal-import Control.Lens.Type-import Control.Lens.IndexedLens-import Control.Monad-import Data.Char (toLower)-import Data.Either (lefts)-import Data.Foldable hiding (concat)-import Data.Function (on)-import Data.List as List-import Data.Map as Map hiding (toList,map,filter)-import Data.Maybe (isNothing,isJust,catMaybes,fromJust)-import Data.Ord (comparing)-import Data.Set as Set hiding (toList,map,filter)-import Data.Set.Lens-import Data.Traversable hiding (mapM)-import Language.Haskell.TH-import Language.Haskell.TH.Lens---- | Flags for lens construction-data LensFlag-  = SimpleLenses-  | PartialLenses-  | BuildTraversals-  | SingletonAndField-  | SingletonIso-  | HandleSingletons-  | SingletonRequired-  | CreateClass-  | CreateInstance-  | ClassRequired-  deriving (Eq,Ord,Show,Read)---- | Only Generate valid 'Simple' 'Lens' lenses.-simpleLenses      :: Simple Lens LensRules Bool-simpleLenses       = lensFlags.contains SimpleLenses---- | Enables the generation of partial lenses, generating runtime errors for--- every constructor that does not have a valid definition for the lens. This--- occurs when the constructor lacks the field, or has multiple fields mapped--- to the same lens.-partialLenses     :: Simple Lens LensRules Bool-partialLenses      = lensFlags.contains PartialLenses---- | In the situations that a lens would be partial, when 'partialLenses' is--- used, this flag instead causes traversals to be generated.  Only one can be--- used, and if neither are, then compile-time errors are generated.-buildTraversals   :: Simple Lens LensRules Bool-buildTraversals    = lensFlags.contains BuildTraversals---- | Handle singleton constructors specially.-handleSingletons  :: Simple Lens LensRules Bool-handleSingletons   = lensFlags.contains HandleSingletons---- | When building a singleton 'Iso' (or 'Lens') for a record constructor, build both--- the 'Iso' (or 'Lens') for the record and the one for the field.-singletonAndField :: Simple Lens LensRules Bool-singletonAndField  = lensFlags.contains SingletonAndField---- | Use 'Iso' for singleton constructors.-singletonIso      :: Simple Lens LensRules Bool-singletonIso       = lensFlags.contains SingletonIso---- | Expect a single constructor, single field newtype or data type.-singletonRequired :: Simple Lens LensRules Bool-singletonRequired  = lensFlags.contains SingletonRequired---- | Create the class if the constructor is simple and the 'lensClass' rule matches.-createClass       :: Simple Lens LensRules Bool-createClass        = lensFlags.contains CreateClass---- | Create the instance if the constructor is simple and the 'lensClass' rule matches.-createInstance    :: Simple Lens LensRules Bool-createInstance     = lensFlags.contains CreateInstance---- | Die if the 'lensClass' fails to match.-classRequired     :: Simple Lens LensRules Bool-classRequired      = lensFlags.contains ClassRequired---- | This configuration describes the options we'll be using to make isomorphisms or lenses.-data LensRules = LensRules-  { _lensIso   :: String -> Maybe String-  , _lensField :: String -> Maybe String-  , _lensClass :: String -> Maybe (String, String)-  , _lensFlags :: Set LensFlag-  }---- | Lens to access the convention for naming top level isomorphisms in our lens rules.------ Defaults to lowercasing the first letter of the constructor.-lensIso :: Simple Lens LensRules (String -> Maybe String)-lensIso f (LensRules i n c o) = (\i' -> LensRules i' n c o) <$> f i---- | Lens to access the convention for naming fields in our lens rules.------ Defaults to stripping the _ off of the field name, lowercasing the name, and--- rejecting the field if it doesn't start with an '_'.-lensField :: Simple Lens LensRules (String -> Maybe String)-lensField f (LensRules i n c o) = (\n' -> LensRules i n' c o) <$> f n---- | Retrieve options such as the name of the class and method to put in it to--- build a class around monomorphic data types.-lensClass :: Simple Lens LensRules (String -> Maybe (String, String))-lensClass f (LensRules i n c o) = (\c' -> LensRules i n c' o) <$> f c---- | Retrieve options such as the name of the class and method to put in it to--- build a class around monomorphic data types.-lensFlags :: Simple Lens LensRules (Set LensFlag)-lensFlags f (LensRules i n c o) = LensRules i n c <$> f o---- | Default lens rules-defaultRules :: LensRules-defaultRules = LensRules top field (const Nothing) $-    Set.fromList [SingletonIso, SingletonAndField, CreateClass, CreateInstance, BuildTraversals]-  where-    top (c:cs) = Just (toLower c:cs)-    top _      = Nothing-    field ('_':c:cs) = Just (toLower c:cs)-    field _          = Nothing---- | Rules for making fairly simple partial lenses, ignoring the special cases--- for isomorphisms and traversals, and not making any classes.-lensRules :: LensRules-lensRules = defaultRules-  % lensIso          .~ const Nothing-  % lensClass        .~ const Nothing-  % handleSingletons .~ True-  % partialLenses    .~ False-  % buildTraversals  .~ True---- | Rules for making lenses and traversals that precompose another lens.-classyRules :: LensRules-classyRules = defaultRules-  % lensIso .~ const Nothing-  % handleSingletons .~ False-  % lensClass .~ classy-  % classRequired .~ True-  % partialLenses .~ False-  % buildTraversals .~ True-  where-    classy :: String -> Maybe (String, String)-    classy n@(a:as) = Just ("Has" ++ n, toLower a:as)-    classy _ = Nothing---- | Rules for making an isomorphism from a data type-isoRules :: LensRules-isoRules = defaultRules-  % singletonRequired .~ True-  % singletonAndField .~ True---- | Build lenses (and traversals) with a sensible default configuration.------ > makeLenses = makeLensesWith lensRules-makeLenses :: Name -> Q [Dec]-makeLenses = makeLensesWith lensRules---- | Make lenses and traversals for a type, and create a class when the type has no arguments.------ /e.g./------ @--- data Foo = Foo { _fooX, _fooY :: 'Int' }--- 'makeClassy' ''Foo--- @------ will create------ @--- class HasFoo t where---   foo :: 'Simple' 'Lens' t Foo--- instance HasFoo Foo where foo = 'id'--- fooX, fooY :: HasFoo t => 'Simple' 'Lens' t 'Int'--- @------ > makeClassy = makeLensesWith classyRules-makeClassy :: Name -> Q [Dec]-makeClassy = makeLensesWith classyRules---- | Make a top level isomorphism injecting /into/ the type.------ The supplied name is required to be for a type with a single constructor that has a single argument------ /e.g./------ @--- newtype List a = List [a]--- makeIso ''List--- @------ will create------ @--- list :: Iso [a] [b] ('List' a) ('List' b)--- @------ > makeIso = makeLensesWith isoRules-makeIso :: Name -> Q [Dec]-makeIso = makeLensesWith isoRules---- | Derive lenses and traversals, specifying explicit pairings of @(fieldName, lensName)@.------ If you map multiple names to the same label, and it is present in the same constructor then this will generate a 'Traversal'.------ /e.g./------ > makeLensesFor [("_foo", "fooLens"), ("baz", "lbaz")] ''Foo--- > makeLensesFor [("_barX", "bar"), ("_barY", "bar)] ''Bar-makeLensesFor :: [(String, String)] -> Name -> Q [Dec]-makeLensesFor fields = makeLensesWith $ lensRules % lensField .~ (`Prelude.lookup` fields)---- | Derive lenses and traversals, using a named wrapper class, and specifying--- explicit pairings of @(fieldName, traversalName)@.------ Example usage:------ > makeClassyFor "HasFoo" "foo" [("_foo", "fooLens"), ("bar", "lbar")] ''Foo-makeClassyFor :: String -> String -> [(String, String)] -> Name -> Q [Dec]-makeClassyFor clsName funName fields = makeLensesWith $ classyRules-  % lensClass .~ const (Just (clsName,funName))-  % lensField .~ (`Prelude.lookup` fields)---- | Build lenses with a custom configuration.-makeLensesWith :: LensRules -> Name -> Q [Dec]-makeLensesWith cfg nm = do-    inf <- reify nm-    case inf of-      (TyConI decl) -> case deNewtype decl of-        (DataD ctx tyConName args cons _) -> case cons of-          [NormalC dataConName [(    _,ty)]]-            | cfg^.handleSingletons  -> makeIsoLenses cfg ctx tyConName args dataConName Nothing ty-          [RecC    dataConName [(fld,_,ty)]]-            | cfg^.handleSingletons  -> makeIsoLenses cfg ctx tyConName args dataConName (Just fld) ty-          _ | cfg^.singletonRequired -> fail "makeLensesWith: A single-constructor single-argument data type is required"-            | otherwise              -> makeFieldLenses cfg ctx tyConName args cons-        _ -> fail "makeLensesWith: Unsupported data type"-      _ -> fail "makeLensesWith: Expected the name of a data type or newtype"-  where-    deNewtype (NewtypeD ctx tyConName args c d) = DataD ctx tyConName args [c] d-    deNewtype d = d---------------------------------------------------------------------------------- Internal TH Implementation---------------------------------------------------------------------------------- | Given a set of names, build a map from those names to a set of fresh names based on them.-freshMap :: Set Name -> Q (Map Name Name)-freshMap ns = Map.fromList <$> for (toList ns) (\ n -> (,) n <$> newName (nameBase n))--makeIsoTo :: Name -> ExpQ-makeIsoTo conName = do-  f <- newName "f"-  a <- newName "a"-  lamE [varP f, conP conName [varP a]] $-    appsE [ return (VarE 'fmap)-          , conE conName-          , varE f `appE` varE a-          ]--makeIsoFrom :: Name -> ExpQ-makeIsoFrom conName = do-  f <- newName "f"-  a <- newName "a"-  b <- newName "b"-  lamE [varP f, varP a] $-    appsE [ return (VarE 'fmap)-          , lamE [conP conName [varP b]] $ varE b-          , varE f `appE` (conE conName `appE` varE a)-          ]--makeIsoBody :: Name -> Name -> (Name -> ExpQ) -> (Name -> ExpQ) -> DecQ-makeIsoBody lensName conName f g = funD lensName [clause [] (normalB body) []] where-  body = appsE [ return (VarE 'isomorphic)-               , f conName-               , g conName-               ]--makeLensBody :: Name -> Name -> (Name -> ExpQ) -> (Name -> ExpQ) -> DecQ-makeLensBody lensName conName f _ = funD lensName [clause [] (normalB (f conName)) []]--plain :: TyVarBndr -> TyVarBndr-plain (KindedTV t _) = PlainTV t-plain (PlainTV t) = PlainTV t--appArgs :: Type -> [TyVarBndr] -> Type-appArgs t [] = t-appArgs t (x:xs) = appArgs (AppT t (VarT (x^.name))) xs--apps :: Type -> [Type] -> Type-apps = Prelude.foldl AppT--appsT :: TypeQ -> [TypeQ] -> TypeQ-appsT = Prelude.foldl appT---- | Given------ > newtype Cxt b => Foo a b c d = Foo { _baz :: Bar a b }------ This will generate:------ > foo :: (Cxt b, Cxt f) => Iso (Foo a b c d) (Foo e f g h) (Bar a b) (Bar e f)--- > foo = isomorphic (\f a -> (\(Foo b) -> b) <$> f (Foo a))--- >                  (\f (Foo a) -> fmap Foo (f a))--- > {-# INLINE foo #-}---- > baz :: (Cxt b, Cxt f) => Iso (Bar a b) (Bar e f) (Foo a b c d) (Foo e f g h)--- > baz = isomorphic (\f (Foo a) -> fmap Foo (f a))--- >                  (\f a -> fmap (\(Foo b) -> b) (f (Foo a)))--- > {-# INLINE baz #-}-makeIsoLenses :: LensRules-              -> Cxt-              -> Name-              -> [TyVarBndr]-              -> Name-              -> Maybe Name-              -> Type-              -> Q [Dec]-makeIsoLenses cfg ctx tyConName tyArgs0 dataConName maybeFieldName partTy = do-  let tyArgs = map plain tyArgs0-  m <- freshMap $ setOf typeVars tyArgs-  let aty = partTy-      bty = substTypeVars m aty-      cty = appArgs (ConT tyConName) tyArgs-      dty = substTypeVars m cty-      quantified = ForallT (tyArgs ++ substTypeVars m tyArgs) (ctx ++ substTypeVars m ctx)-      maybeIsoName = mkName <$> view lensIso cfg (nameBase dataConName)-      lensOnly = not $ cfg^.singletonIso-      isoCon   | lensOnly  = ConT ''Lens-               | otherwise = ConT ''Iso-      makeBody | lensOnly  = makeLensBody-               | otherwise = makeIsoBody-  isoDecls <- flip (maybe (return [])) maybeIsoName $ \isoName -> do-    let decl = SigD isoName $ quantified $ isoCon `apps`-          if cfg^.simpleLenses then [aty,aty,cty,cty] else [aty,bty,cty,dty]-    body <- makeBody isoName dataConName makeIsoFrom makeIsoTo-#ifndef INLINING-    return [decl, body]-#else-    inlining <- inlinePragma isoName-    return [decl, body, inlining]-#endif-  accessorDecls <- case mkName <$> (maybeFieldName >>= view lensField cfg . nameBase) of-    jfn@(Just lensName)-      | (jfn /= maybeIsoName) && (isNothing maybeIsoName || cfg^.singletonAndField) -> do-      let decl = SigD lensName $ quantified $ isoCon `apps`-                   if cfg^.simpleLenses then [cty,cty,aty,aty]-                                        else [cty,dty,aty,bty]-      body <- makeBody lensName dataConName makeIsoTo makeIsoFrom-#ifndef INLINING-      return [decl, body]-#else-      inlining <- inlinePragma lensName-      return [decl, body, inlining]-#endif-    _ -> return []-  return $ isoDecls ++ accessorDecls--makeFieldLensBody :: Bool -> Name -> [(Con, [Name])] -> Maybe Name -> Q Dec-makeFieldLensBody isTraversal lensName conList maybeMethodName = case maybeMethodName of-    Just methodName -> do-       go <- newName "go"-       let expr = infixApp (varE methodName) (varE '(Prelude..)) (varE go)-       funD lensName [ clause [] (normalB expr) [funD go clauses] ]-    Nothing -> funD lensName clauses-  where-    clauses = map buildClause conList-    buildClause (con, fields) = do-      f <- newName "_f"-      vars <- for (con^..conNamedFields._1) $ \field ->-          if field `List.elem` fields-        then Left  <$> ((,) <$> newName ('_':(nameBase field++"'")) <*> newName ('_':nameBase field))-        else Right <$> newName ('_':nameBase field)-      let cpats = map (varP . either fst id) vars               -- Deconstruction-          cvals = map (varE . either snd id) vars               -- Reconstruction-          fpats = map (varP . snd)                 $ lefts vars -- Lambda patterns-          fvals = map (appE (varE f) . varE . fst) $ lefts vars -- Functor applications-          conName = con^.name-          recon = appsE $ conE conName : cvals--          expr-            | not isTraversal && length fields /= 1-              = appE (varE 'error) . litE . stringL-              $ show lensName ++ ": expected a single matching field in " ++ show conName ++ ", found " ++ show (length fields)-            | List.null fields-              = appE (varE 'pure) recon-            | otherwise-              = let step Nothing r = Just $ infixE (Just $ lamE fpats recon) (varE '(<$>)) (Just r)-                    step (Just l) r = Just $ infixE (Just l) (varE '(<*>)) (Just r)-                in  fromJust $ List.foldl step Nothing fvals-              -- = infixE (Just $ lamE fpats recon) (varE '(<$>)) $ Just $ List.foldl1 (\l r -> infixE (Just l) (varE '(<*>)) (Just r)) fvals-      clause [varP f, conP conName cpats] (normalB expr) []--makeFieldLenses :: LensRules-                -> Cxt         -- ^ surrounding cxt driven by the data type context-                -> Name        -- ^ data/newtype constructor name-                -> [TyVarBndr] -- ^ args-                -> [Con]-                -> Q [Dec]-makeFieldLenses cfg ctx tyConName tyArgs0 cons = do-  let tyArgs = map plain tyArgs0-      maybeLensClass = do-        guard $ tyArgs == []-        view lensClass cfg $ nameBase tyConName-      maybeClassName = fmap (^._1.to mkName) maybeLensClass-  t <- newName "t"-  a <- newName "a"-    -  --TODO: there's probably a more efficient way to do this.-  lensFields <- map (\xs -> (fst $ head xs, map snd xs))-              . groupBy ((==) `on` fst) . sortBy (comparing fst)-              . concat-            <$> mapM (getLensFields $ view lensField cfg) cons--  -- varMultiSet knows how many usages of the type variables there are.-  let varMultiSet = List.concatMap (toListOf (conFields._2.typeVars)) cons-      varSet = Set.fromList $ map (view name) tyArgs--  bodies <- for lensFields $ \(lensName, fields) -> do-    let fieldTypes = map (view _3) fields-    -- All of the polymorphic variables not involved in these fields-        otherVars = varMultiSet List.\\ fieldTypes^..typeVars-    -- New type variable binders, and the type to represent the selected fields-    (tyArgs', cty) <- unifyTypes tyArgs fieldTypes-    -- Map for the polymorphic variables that are only involved in these fields, to new names for them.-    m <- freshMap . Set.difference varSet $ Set.fromList otherVars-    let aty | isJust maybeClassName = VarT t-            | otherwise             = appArgs (ConT tyConName) tyArgs'-        bty = substTypeVars m aty-        dty = substTypeVars m cty--        s = setOf folded m-        relevantBndr b = s^.contains (b^.name)-        relevantCtx = not . Set.null . Set.intersection s . setOf typeVars-        tvs = tyArgs' ++ filter relevantBndr (substTypeVars m tyArgs')-        ps = ctx ++ filter relevantCtx (substTypeVars m ctx)-        qs = case maybeClassName of-           Just n | not (cfg^.createClass) -> ClassP n [VarT t] : ps-           _                               -> ps-        tvs' | isJust maybeClassName && not (cfg^.createClass) = PlainTV t : tvs-             | otherwise                                       = tvs--        --TODO: Better way to write this?-        fieldMap = fromListWith (++) $ map (\(cn,fn,_) -> (cn, [fn])) fields-        conList = map (\c -> (c, Map.findWithDefault [] (view name c) fieldMap)) cons-        maybeMethodName = fmap (mkName . view _2) maybeLensClass--    isTraversal <- do-      let notSingular = filter ((/= 1) . length . snd) conList-          showCon (c, fs) = pprint (view name c) ++ " { " ++ concat (intersperse ", " $ map pprint fs) ++ " }"-      case (cfg^.buildTraversals, cfg^.partialLenses) of-        (True,  True) -> fail "Cannot makeLensesWith both of the flags buildTraversals and partialLenses."-        (False, True) -> return False-        (True,  False) | List.null notSingular -> return False-                       | otherwise -> return True-        (False, False) | List.null notSingular -> return False-                       | otherwise -> fail . unlines $-          [ "Cannot use 'makeLensesWith' with constructors that don't map just one field"-          , "to a lens, without using either the buildTraversals or partialLenses flags."-          , if length conList == 1-            then "The following constructor failed this criterion for the " ++ pprint lensName ++ " lens:"-            else "The following constructors failed this criterion for the " ++ pprint lensName ++ " lens:"-          ] ++ map showCon conList--    --TODO: consider detecting simpleLenses, and generating signatures involving "Simple"?-    let decl = SigD lensName-             . ForallT tvs' qs-             . apps (if isTraversal then ConT ''Traversal else ConT ''Lens)-             $ if cfg^.simpleLenses then [aty,aty,cty,cty] else [aty,bty,cty,dty]--    body <- makeFieldLensBody isTraversal lensName conList maybeMethodName-#ifndef INLINING-    return [decl, body]-#else-    inlining <- inlinePragma lensName-    return [decl, body, inlining]-#endif-  let defs = Prelude.concat bodies-  case maybeLensClass of-    Nothing -> return defs-    Just (clsNameString, methodNameString) -> do-      let clsName    = mkName clsNameString-          methodName = mkName methodNameString-      Prelude.sequence $-        filter (\_ -> cfg^.createClass) [-          classD (return []) clsName [PlainTV t] [] (-            sigD methodName (appsT (conT ''Lens) [varT t, varT t, conT tyConName, conT tyConName]) :-            map return defs)]-        ++ filter (\_ -> cfg^.createInstance) [-          instanceD (return []) (conT clsName `appT` conT tyConName) [-            funD methodName [clause [varP a] (normalB (varE a)) []]-#ifdef INLINING-            , inlinePragma methodName-#endif-            ]]-        ++ filter (\_ -> not $ cfg^.createClass) (map return defs)---- | Gets @[(lens name, (constructor name, field name, type))]@ from a record constructor-getLensFields :: (String -> Maybe String) -> Con -> Q [(Name, (Name, Name, Type))]-getLensFields f (RecC cn fs)-  = return . catMaybes-  $ map (\(fn,_,t) -> (\ln -> (mkName ln, (cn,fn,t))) <$> f (nameBase fn)) fs-getLensFields _ _-  = return []---- TODO: properly fill this out------ Ideally this would unify the different field types, and figure out which polymorphic variables--- need to be the same.  For now it just leaves them the same and yields the first type.--- (This leaves us open to inscrutable compile errors in the generated code)-unifyTypes :: [TyVarBndr] -> [Type] -> Q ([TyVarBndr], Type)-unifyTypes tvs tys = return (tvs, head tys)--#if !(MIN_VERSION_template_haskell(2,7,0))--- | The orphan instance for old versions is bad, but programing without 'Applicative' is worse.-instance Applicative Q where-  pure = return-  (<*>) = ap-#endif--#ifdef INLINING--inlinePragma :: Name -> Q Dec-#if MIN_VERSION_template_haskell(2,8,0)--# ifdef OLD_INLINE_PRAGMAS--- 7.6rc1?-inlinePragma methodName = pragInlD methodName $ inlineSpecNoPhase Inline False-# else--- 7.7.20120830-inlinePragma methodName = pragInlD methodName Inline FunLike AllPhases-# endif--#else--- GHC <7.6, TH <2.8.0-inlinePragma methodName = pragInlD methodName $ inlineSpecNoPhase True False-#endif--#endif+{-# LANGUAGE PatternGuards #-}+#ifdef TRUSTWORTHY+# if MIN_VERSION_template_haskell(2,12,0)+{-# LANGUAGE Safe #-}+# else+{-# LANGUAGE Trustworthy #-}+# endif+#endif++#include "lens-common.h"++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.TH+-- Copyright   :  (C) 2012-16 Edward Kmett, 2012-13 Michael Sloan+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-----------------------------------------------------------------------------+module Control.Lens.TH+  (+  -- * Constructing Lenses Automatically+  -- ** Lenses for data fields+    makeLenses, makeLensesFor+  , makeClassy, makeClassyFor, makeClassy_+  , makeFields+  , makeFieldsNoPrefix+  , makeFieldsId+  -- ** Prisms+  , makePrisms+  , makeClassyPrisms+  -- ** Wrapped+  , makeWrapped+  -- * Constructing Lenses Given a Declaration Quote+  -- ** Lenses for data fields+  , declareLenses, declareLensesFor+  , declareClassy, declareClassyFor+  , declareFields+  -- ** Prisms+  , declarePrisms+  -- ** Wrapped+  , declareWrapped+  -- * Configuring Lenses+  -- ** Running LensRules+  , makeLensesWith+  , declareLensesWith+  -- ** LensRules type+  , LensRules+  -- ** Predefined LensRules+  , lensRules+  , lensRulesFor+  , classyRules+  , classyRules_+  , defaultFieldRules+  , camelCaseFields+  , classUnderscoreNoPrefixFields+  , underscoreFields+  , abbreviatedFields+  , classIdFields+  -- ** LensRules configuration accessors+  , lensField+  , FieldNamer+  , DefName(..)+  , lensClass+  , ClassyNamer+  , simpleLenses+  , createClass+  , generateSignatures+  , generateUpdateableOptics+  , generateLazyPatterns+  , generateRecordSyntax+  -- ** FieldNamers+  , underscoreNoPrefixNamer+  , lookingupNamer+  , mappingNamer+  , camelCaseNamer+  , classUnderscoreNoPrefixNamer+  , underscoreNamer+  , abbreviatedNamer+  , classIdNamer+  ) where++import Prelude ()++import Control.Monad.Trans.Class+import Control.Monad.Trans.State+import Control.Monad.Trans.Writer+import Control.Lens.Fold+import Control.Lens.Getter+import Control.Lens.Lens+import Control.Lens.Setter+import Control.Lens.Traversal+import Control.Lens.Internal.Prelude as Prelude+import Control.Lens.Internal.TH+import Control.Lens.Internal.FieldTH+import Control.Lens.Internal.PrismTH+import Control.Lens.Wrapped () -- haddocks+import Control.Lens.Type () -- haddocks+import Data.Char (toLower, toUpper, isUpper)+import Data.Foldable hiding (concat, any)+import qualified Data.List as List+import qualified Data.Map as Map+import Data.Map (Map)+import Data.Maybe (maybeToList)+import qualified Data.Set as Set+import Data.Set (Set)+import Data.Traversable hiding (mapM)+import Language.Haskell.TH.Datatype+import Language.Haskell.TH.Lens+import Language.Haskell.TH.Lib+import Language.Haskell.TH.Syntax hiding (lift)++-- | Generate "simple" optics even when type-changing optics are possible.+-- (e.g. 'Lens'' instead of 'Lens')+simpleLenses :: Lens' LensRules Bool+simpleLenses f r = fmap (\x -> r { _simpleLenses = x}) (f (_simpleLenses r))++-- | Indicate whether or not to supply the signatures for the generated+-- lenses.+--+-- Disabling this can be useful if you want to provide a more restricted type+-- signature or if you want to supply hand-written haddocks.+generateSignatures :: Lens' LensRules Bool+generateSignatures f r =+  fmap (\x -> r { _generateSigs = x}) (f (_generateSigs r))++-- | Generate "updateable" optics when 'True'. When 'False', 'Fold's will be+-- generated instead of 'Traversal's and 'Getter's will be generated instead+-- of 'Lens'es. This mode is intended to be used for types with invariants+-- which must be maintained by "smart" constructors.+generateUpdateableOptics :: Lens' LensRules Bool+generateUpdateableOptics f r =+  fmap (\x -> r { _allowUpdates = x}) (f (_allowUpdates r))++-- | Generate optics using lazy pattern matches. This can+-- allow fields of an undefined value to be initialized with lenses:+--+-- @+-- data Foo = Foo {_x :: Int, _y :: Bool}+--   deriving Show+--+-- 'makeLensesWith' ('lensRules' & 'generateLazyPatterns' .~ True) ''Foo+-- @+--+-- @+-- > undefined & x .~ 8 & y .~ True+-- Foo {_x = 8, _y = True}+-- @+--+-- The downside of this flag is that it can lead to space-leaks and+-- code-size/compile-time increases when generated for large records. By+-- default this flag is turned off, and strict optics are generated.+--+-- When using lazy optics the strict optic can be recovered by composing+-- with '$!':+--+-- @+-- strictOptic = ($!) . lazyOptic+-- @+generateLazyPatterns :: Lens' LensRules Bool+generateLazyPatterns f r =+  fmap (\x -> r { _lazyPatterns = x}) (f (_lazyPatterns r))++generateRecordSyntax :: Lens' LensRules Bool+generateRecordSyntax f r =+  fmap (\x -> r {_recordSyntax = x}) (f (_recordSyntax r))++-- | Create the class if the constructor is 'Control.Lens.Type.Simple' and the+-- 'lensClass' rule matches.+createClass :: Lens' LensRules Bool+createClass f r =+  fmap (\x -> r { _generateClasses = x}) (f (_generateClasses r))++-- | 'Lens'' to access the convention for naming fields in our 'LensRules'.+lensField :: Lens' LensRules FieldNamer+lensField f r = fmap (\x -> r { _fieldToDef = x}) (f (_fieldToDef r))++-- | 'Lens'' to access the option for naming "classy" lenses.+lensClass :: Lens' LensRules ClassyNamer+lensClass f r = fmap (\x -> r { _classyLenses = x }) (f (_classyLenses r))++-- | Rules for making fairly simple partial lenses, ignoring the special cases+-- for isomorphisms and traversals, and not making any classes.+-- It uses 'underscoreNoPrefixNamer'.+lensRules :: LensRules+lensRules = LensRules+  { _simpleLenses    = False+  , _generateSigs    = True+  , _generateClasses = False+  , _allowIsos       = True+  , _allowUpdates    = True+  , _lazyPatterns    = False+  , _recordSyntax    = False+  , _classyLenses    = const Nothing+  , _fieldToDef      = underscoreNoPrefixNamer+  }++-- | A 'FieldNamer' that strips the _ off of the field name,+-- lowercases the name, and skips the field if it doesn't start with+-- an '_'.+underscoreNoPrefixNamer :: FieldNamer+underscoreNoPrefixNamer _ _ n =+  case nameBase n of+    '_':x:xs -> [TopName (mkName (toLower x:xs))]+    _        -> []+++-- | Construct a 'LensRules' value for generating top-level definitions+-- using the given map from field names to definition names.+lensRulesFor ::+  [(String, String)] {- ^ [(Field Name, Definition Name)] -} ->+  LensRules+lensRulesFor fields = lensRules & lensField .~ lookingupNamer fields++-- | Create a 'FieldNamer' from explicit pairings of @(fieldName, lensName)@.+lookingupNamer :: [(String,String)] -> FieldNamer+lookingupNamer kvs _ _ field =+  [ TopName (mkName v) | (k,v) <- kvs, k == nameBase field]++-- | Create a 'FieldNamer' from a mapping function. If the function+-- returns @[]@, it creates no lens for the field.+mappingNamer :: (String -> [String]) -- ^ A function that maps a @fieldName@ to @lensName@s.+             -> FieldNamer+mappingNamer mapper _ _ = fmap (TopName . mkName) . mapper . nameBase++-- | Rules for making lenses and traversals that precompose another 'Lens'.+classyRules :: LensRules+classyRules = LensRules+  { _simpleLenses    = True+  , _generateSigs    = True+  , _generateClasses = True+  , _allowIsos       = False -- generating Isos would hinder "subtyping"+  , _allowUpdates    = True+  , _lazyPatterns    = False+  , _recordSyntax    = False+  , _classyLenses    = \n ->+        case nameBase n of+          x:xs -> Just (mkName ("Has" ++ x:xs), mkName (toLower x:xs))+          []   -> Nothing+  , _fieldToDef      = underscoreNoPrefixNamer+  }++-- | Rules for making lenses and traversals that precompose another 'Lens'+-- using a custom function for naming the class, main class method, and a+-- mapping from field names to definition names.+classyRulesFor+  :: (String -> Maybe (String, String)) {- ^ Type Name -> Maybe (Class Name, Method Name) -} ->+  [(String, String)] {- ^ [(Field Name, Method Name)] -} ->+  LensRules+classyRulesFor classFun fields = classyRules+  & lensClass .~ (over (mapped . both) mkName . classFun . nameBase)+  & lensField .~ lookingupNamer fields++-- | A 'LensRules' used by 'makeClassy_'.+classyRules_ :: LensRules+classyRules_+  = classyRules & lensField .~ \_ _ n -> [TopName (mkName ('_':nameBase n))]++-- | Build lenses (and traversals) with a sensible default configuration.+--+-- /e.g./+--+-- @+-- data FooBar+--   = Foo { _x, _y :: 'Int' }+--   | Bar { _x :: 'Int' }+-- 'makeLenses' ''FooBar+-- @+--+-- will create+--+-- @+-- x :: 'Lens'' FooBar 'Int'+-- x f (Foo a b) = (\\a\' -> Foo a\' b) \<$\> f a+-- x f (Bar a)   = Bar \<$\> f a+-- y :: 'Traversal'' FooBar 'Int'+-- y f (Foo a b) = (\\b\' -> Foo a  b\') \<$\> f b+-- y _ c\@(Bar _) = pure c+-- @+--+-- @+-- 'makeLenses' = 'makeLensesWith' 'lensRules'+-- @+makeLenses :: Name -> DecsQ+makeLenses = makeFieldOptics lensRules++-- | Make lenses and traversals for a type, and create a class when the+-- type has no arguments.+--+-- /e.g./+--+-- @+-- data Foo = Foo { _fooX, _fooY :: 'Int' }+-- 'makeClassy' ''Foo+-- @+--+-- will create+--+-- @+-- class HasFoo t where+--   foo :: 'Lens'' t Foo+--   fooX :: 'Lens'' t 'Int'+--   fooX = foo . go where go f (Foo x y) = (\\x\' -> Foo x' y) \<$\> f x+--   fooY :: 'Lens'' t 'Int'+--   fooY = foo . go where go f (Foo x y) = (\\y\' -> Foo x y') \<$\> f y+-- instance HasFoo Foo where+--   foo = id+-- @+--+-- @+-- 'makeClassy' = 'makeLensesWith' 'classyRules'+-- @+makeClassy :: Name -> DecsQ+makeClassy = makeFieldOptics classyRules++-- | Make lenses and traversals for a type, and create a class when the type+-- has no arguments.  Works the same as 'makeClassy' except that (a) it+-- expects that record field names do not begin with an underscore, (b) all+-- record fields are made into lenses, and (c) the resulting lens is prefixed+-- with an underscore.+makeClassy_ :: Name -> DecsQ+makeClassy_ = makeFieldOptics classyRules_++-- | Derive lenses and traversals, specifying explicit pairings+-- of @(fieldName, lensName)@.+--+-- If you map multiple names to the same label, and it is present in the same+-- constructor then this will generate a 'Traversal'.+--+-- /e.g./+--+-- @+-- 'makeLensesFor' [(\"_foo\", \"fooLens\"), (\"baz\", \"lbaz\")] ''Foo+-- 'makeLensesFor' [(\"_barX\", \"bar\"), (\"_barY\", \"bar\")] ''Bar+-- @+makeLensesFor :: [(String, String)] -> Name -> DecsQ+makeLensesFor fields = makeFieldOptics (lensRulesFor fields)++-- | Derive lenses and traversals, using a named wrapper class, and+-- specifying explicit pairings of @(fieldName, traversalName)@.+--+-- Example usage:+--+-- @+-- 'makeClassyFor' \"HasFoo\" \"foo\" [(\"_foo\", \"fooLens\"), (\"bar\", \"lbar\")] ''Foo+-- @+makeClassyFor :: String -> String -> [(String, String)] -> Name -> DecsQ+makeClassyFor clsName funName fields = makeFieldOptics $+  classyRulesFor (const (Just (clsName, funName))) fields++-- | Build lenses with a custom configuration.+makeLensesWith :: LensRules -> Name -> DecsQ+makeLensesWith = makeFieldOptics++++-- | Make lenses for all records in the given declaration quote. All record+-- syntax in the input will be stripped off.+--+-- /e.g./+--+-- @+-- declareLenses [d|+--   data Foo = Foo { fooX, fooY :: 'Int' }+--     deriving 'Show'+--   |]+-- @+--+-- will create+--+-- @+-- data Foo = Foo 'Int' 'Int' deriving 'Show'+-- fooX, fooY :: 'Lens'' Foo Int+-- @+declareLenses :: DecsQ -> DecsQ+declareLenses+  = declareLensesWith+  $ lensRules+  & lensField .~ \_ _ n -> [TopName n]++-- | Similar to 'makeLensesFor', but takes a declaration quote.+declareLensesFor :: [(String, String)] -> DecsQ -> DecsQ+declareLensesFor fields+  = declareLensesWith+  $ lensRulesFor fields+  & lensField .~ \_ _ n -> [TopName n]++-- | For each record in the declaration quote, make lenses and traversals for+-- it, and create a class when the type has no arguments. All record syntax+-- in the input will be stripped off.+--+-- /e.g./+--+-- @+-- declareClassy [d|+--   data Foo = Foo { fooX, fooY :: 'Int' }+--     deriving 'Show'+--   |]+-- @+--+-- will create+--+-- @+-- data Foo = Foo 'Int' 'Int' deriving 'Show'+-- class HasFoo t where+--   foo :: 'Lens'' t Foo+-- instance HasFoo Foo where foo = 'id'+-- fooX, fooY :: HasFoo t => 'Lens'' t 'Int'+-- @+declareClassy :: DecsQ -> DecsQ+declareClassy+  = declareLensesWith+  $ classyRules+  & lensField .~ \_ _ n -> [TopName n]++-- | Similar to 'makeClassyFor', but takes a declaration quote.+declareClassyFor ::+  [(String, (String, String))] -> [(String, String)] -> DecsQ -> DecsQ+declareClassyFor classes fields+  = declareLensesWith+  $ classyRulesFor (`Prelude.lookup`classes) fields+  & lensField .~ \_ _ n -> [TopName n]++-- | Generate a 'Control.Lens.Type.Prism' for each constructor of each data type.+--+-- /e.g./+--+-- @+-- declarePrisms [d|+--   data Exp = Lit Int | Var String | Lambda{ bound::String, body::Exp }+--   |]+-- @+--+-- will create+--+-- @+-- data Exp = Lit Int | Var String | Lambda { bound::String, body::Exp }+-- _Lit :: 'Prism'' Exp Int+-- _Var :: 'Prism'' Exp String+-- _Lambda :: 'Prism'' Exp (String, Exp)+-- @+declarePrisms :: DecsQ -> DecsQ+declarePrisms = declareWith $ \dec -> do+  emit =<< liftDeclare (makeDecPrisms True dec)+  return dec++-- | Build 'Control.Lens.Wrapped.Wrapped' instance for each newtype.+declareWrapped :: DecsQ -> DecsQ+declareWrapped = declareWith $ \dec -> do+  maybeDecs <- liftDeclare $ do+    inf <- normalizeDec dec+    makeWrappedForDatatypeInfo inf+  forM_ maybeDecs emit+  return dec++-- | @ declareFields = 'declareLensesWith' 'defaultFieldRules' @+declareFields :: DecsQ -> DecsQ+declareFields = declareLensesWith defaultFieldRules++-- | Declare lenses for each records in the given declarations, using the+-- specified 'LensRules'. Any record syntax in the input will be stripped+-- off.+declareLensesWith :: LensRules -> DecsQ -> DecsQ+declareLensesWith rules = declareWith $ \dec -> do+  emit =<< lift (makeFieldOpticsForDec' rules dec)+  return $ stripFields dec++-----------------------------------------------------------------------------+-- Internal TH Implementation+-----------------------------------------------------------------------------++-- | Given a set of names, build a map from those names to a set of fresh names+-- based on them.+freshMap :: Set Name -> Q (Map Name Name)+freshMap ns = Map.fromList <$> for (toList ns) (\ n -> (,) n <$> newName (nameBase n))+++apps :: Type -> [Type] -> Type+apps = Prelude.foldl AppT+++-- | Build 'Wrapped' instance for a given newtype+makeWrapped :: Name -> DecsQ+makeWrapped nm = do+  inf <- reifyDatatype nm+  maybeDecs <- makeWrappedForDatatypeInfo inf+  maybe (fail "makeWrapped: Unsupported data type") return maybeDecs++makeWrappedForDatatypeInfo :: DatatypeInfo -> Q (Maybe [Dec])+makeWrappedForDatatypeInfo dataInfo@(DatatypeInfo{datatypeCons = cons})+  | [conInfo@(ConstructorInfo{constructorFields = fields})] <- cons+  , [field] <- fields+  = do wrapped   <- makeWrappedInstance dataInfo conInfo field+       rewrapped <- makeRewrappedInstance dataInfo+       return (Just [rewrapped, wrapped])++  | otherwise = return Nothing++makeRewrappedInstance :: DatatypeInfo -> DecQ+makeRewrappedInstance dataInfo = do++   t <- varT <$> newName "t"++   let typeArgs = map (view name) (datatypeVars dataInfo)++   typeArgs' <- do+     m <- freshMap (Set.fromList typeArgs)+     return (substTypeVars m typeArgs)++       -- Con a b c...+   let appliedType  = return (applyDatatypeToArgs dataInfo (map VarT typeArgs))++       -- Con a' b' c'...+       appliedType' = return (applyDatatypeToArgs dataInfo (map VarT typeArgs'))++       -- Con a' b' c'... ~ t+       eq = AppT. AppT EqualityT <$> appliedType' <*> t++       -- Rewrapped (Con a b c...) t+       klass = conT rewrappedTypeName `appsT` [appliedType, t]++   -- instance (Con a' b' c'... ~ t) => Rewrapped (Con a b c...) t+   instanceD (cxt [eq]) klass []++makeWrappedInstance :: DatatypeInfo -> ConstructorInfo -> Type -> DecQ+makeWrappedInstance dataInfo conInfo fieldType = do++  let conName = constructorName conInfo+  let typeArgs = toListOf typeVars (datatypeVars dataInfo)++  -- Con a b c...+  let appliedType  = applyDatatypeToArgs dataInfo (map VarT typeArgs)++  -- type Unwrapped (Con a b c...) = $fieldType+  let unwrappedATF = tySynInstDCompat unwrappedTypeName Nothing+                       [return appliedType] (return fieldType)++  -- Wrapped (Con a b c...)+  let klass        = conT wrappedTypeName `appT` return appliedType++  -- _Wrapped' = iso (\(Con x) -> x) Con+  let wrapFun      = conE conName+  let unwrapFun    = newName "x" >>= \x -> lam1E (conP conName [varP x]) (varE x)+  let body         = appsE [varE isoValName, unwrapFun, wrapFun]+  let isoMethod    = funD _wrapped'ValName [clause [] (normalB body) []]++  -- instance Wrapped (Con a b c...) where+  --   type Unwrapped (Con a b c...) = fieldType+  --   _Wrapped' = iso (\(Con x) -> x) Con+  instanceD (cxt []) klass [unwrappedATF, isoMethod]++-- | Apply the 'datatypeName' of a 'DatatypeInfo' to some argument 'Type's,+-- which are used to instantiate its 'datatypeVars'.+applyDatatypeToArgs :: DatatypeInfo -> [Type] -> Type+applyDatatypeToArgs di@(DatatypeInfo { datatypeName = nm+                                     , datatypeVars = vars+                                     , datatypeInstTypes = instTypes+                                     }) args =+  apps (ConT nm) $+  -- Drop kind signatures if possible to reduce the likelihood of needing to+  -- enable KindSignatures. The likelihood is already quite small, however.+  -- This function is only used for the benefit of {make,declare}Wrapped, and+  -- one needs to enable TypeFamilies in order for the generated code to+  -- typecheck. Since TypeFamilies implies KindSignatures, dropping kind+  -- signatures is probably not required, but better to be safe then sorry.+  dropSigsIfNonDataFam di $+  applySubstitution (Map.fromList (zip (map tvName vars) args)) instTypes++overHead :: (a -> a) -> [a] -> [a]+overHead _ []     = []+overHead f (x:xs) = f x : xs++-- | Field rules for fields in the form @ _prefix_fieldname @+underscoreFields :: LensRules+underscoreFields = defaultFieldRules & lensField .~ underscoreNamer++-- | A 'FieldNamer' for 'underscoreFields'.+underscoreNamer :: FieldNamer+underscoreNamer _ _ field = maybeToList $ do+  _      <- prefix field'+  method <- niceLens+  cls    <- classNaming+  return (MethodName (mkName cls) (mkName method))+  where+    field' = nameBase field+    prefix ('_':xs) | '_' `List.elem` xs = Just (takeWhile (/= '_') xs)+    prefix _                             = Nothing+    niceLens    = prefix field' <&> \n -> drop (length n + 2) field'+    classNaming = niceLens <&> ("Has_" ++)++-- | Field rules for fields in the form @ prefixFieldname or _prefixFieldname @+-- If you want all fields to be lensed, then there is no reason to use an @_@ before the prefix.+-- If any of the record fields leads with an @_@ then it is assume a field without an @_@ should not have a lens created.+--+-- __Note__: The @prefix@ must be the same as the typename (with the first+-- letter lowercased). This is a change from lens versions before lens 4.5.+-- If you want the old behaviour, use 'makeLensesWith' 'abbreviatedFields'+camelCaseFields :: LensRules+camelCaseFields = defaultFieldRules++-- | A 'FieldNamer' for 'camelCaseFields'.+camelCaseNamer :: FieldNamer+camelCaseNamer tyName fields field = maybeToList $ do++  fieldPart <- List.stripPrefix expectedPrefix (nameBase field)+  method    <- computeMethod fieldPart+  let cls = "Has" ++ fieldPart+  return (MethodName (mkName cls) (mkName method))++  where+  expectedPrefix = optUnderscore ++ overHead toLower (nameBase tyName)++  optUnderscore  = ['_' | any (List.isPrefixOf "_" . nameBase) fields ]++  computeMethod (x:xs) | isUpper x = Just (toLower x : xs)+  computeMethod _                  = Nothing++-- | Field rules for fields in the form @ _fieldname @ (the leading+-- underscore is mandatory).+--+-- __Note__: The primary difference to 'camelCaseFields' is that for+-- @classUnderscoreNoPrefixFields@ the field names are not expected to+-- be prefixed with the type name. This might be the desired behaviour+-- when the @DuplicateRecordFields@ extension is enabled.+classUnderscoreNoPrefixFields :: LensRules+classUnderscoreNoPrefixFields =+  defaultFieldRules & lensField .~ classUnderscoreNoPrefixNamer++-- | A 'FieldNamer' for 'classUnderscoreNoPrefixFields'.+classUnderscoreNoPrefixNamer :: FieldNamer+classUnderscoreNoPrefixNamer _ _ field = maybeToList $ do+  fieldUnprefixed <- List.stripPrefix "_" (nameBase field)+  let className  = "Has" ++ overHead toUpper fieldUnprefixed+      methodName = fieldUnprefixed+  return (MethodName (mkName className) (mkName methodName))++-- | Field rules for fields whose names are to be used verbatim, with no+-- prefixes, no underscores, no transformations of any kind.+classIdFields :: LensRules+classIdFields =+  defaultFieldRules & lensField .~ classIdNamer++-- | A 'FieldNamer' for 'classIdFields'.+classIdNamer :: FieldNamer+classIdNamer _ _ field = [MethodName (mkName className) (mkName fieldName)]+  where+  fieldName = nameBase field+  className = "Has" ++ overHead toUpper fieldName++-- | Field rules fields in the form @ prefixFieldname or _prefixFieldname @+-- If you want all fields to be lensed, then there is no reason to use an @_@ before the prefix.+-- If any of the record fields leads with an @_@ then it is assume a field without an @_@ should not have a lens created.+--+-- Note that @prefix@ may be any string of characters that are not uppercase+-- letters. (In particular, it may be arbitrary string of lowercase letters+-- and numbers) This is the behavior that 'defaultFieldRules' had in lens+-- 4.4 and earlier.+abbreviatedFields :: LensRules+abbreviatedFields = defaultFieldRules { _fieldToDef = abbreviatedNamer }++-- | A 'FieldNamer' for 'abbreviatedFields'.+abbreviatedNamer :: FieldNamer+abbreviatedNamer _ fields field = maybeToList $ do++  fieldPart <- stripMaxLc (nameBase field)+  method    <- computeMethod fieldPart+  let cls = "Has" ++ fieldPart+  return (MethodName (mkName cls) (mkName method))++  where+  stripMaxLc f = do x <- List.stripPrefix optUnderscore f+                    case break isUpper x of+                      (p,s) | List.null p || List.null s -> Nothing+                            | otherwise                  -> Just s+  optUnderscore  = ['_' | any (List.isPrefixOf "_" . nameBase) fields ]++  computeMethod (x:xs) | isUpper x = Just (toLower x : xs)+  computeMethod _                  = Nothing+++-- | Generate overloaded field accessors.+--+-- /e.g/+--+-- @+-- data Foo a = Foo { _fooX :: 'Int', _fooY :: a }+-- newtype Bar = Bar { _barX :: 'Char' }+-- makeFields ''Foo+-- makeFields ''Bar+-- @+--+-- will create+--+-- @+-- _fooXLens :: Lens' (Foo a) Int+-- _fooYLens :: Lens (Foo a) (Foo b) a b+-- class HasX s a | s -> a where+--   x :: Lens' s a+-- instance HasX (Foo a) Int where+--   x = _fooXLens+-- class HasY s a | s -> a where+--   y :: Lens' s a+-- instance HasY (Foo a) a where+--   y = _fooYLens+-- _barXLens :: Iso' Bar Char+-- instance HasX Bar Char where+--   x = _barXLens+-- @+--+-- For details, see 'camelCaseFields'.+--+-- @+-- makeFields = 'makeLensesWith' 'defaultFieldRules'+-- @+makeFields :: Name -> DecsQ+makeFields = makeFieldOptics camelCaseFields++-- | Generate overloaded field accessors based on field names which+-- are only prefixed with an underscore (e.g. '_name'), not+-- additionally with the type name (e.g. '_fooName').+--+-- This might be the desired behaviour in case the+-- @DuplicateRecordFields@ language extension is used in order to get+-- rid of the necessity to prefix each field name with the type name.+--+-- As an example:+--+-- @+-- data Foo a  = Foo { _x :: 'Int', _y :: a }+-- newtype Bar = Bar { _x :: 'Char' }+-- makeFieldsNoPrefix ''Foo+-- makeFieldsNoPrefix ''Bar+-- @+--+-- will create classes+--+-- @+-- class HasX s a | s -> a where+--   x :: Lens' s a+-- class HasY s a | s -> a where+--   y :: Lens' s a+-- @+--+-- together with instances+--+-- @+-- instance HasX (Foo a) Int+-- instance HasY (Foo a) a where+-- instance HasX Bar Char where+-- @+--+-- For details, see 'classUnderscoreNoPrefixFields'.+--+-- @+-- makeFieldsNoPrefix = 'makeLensesWith' 'classUnderscoreNoPrefixFields'+-- @+makeFieldsNoPrefix :: Name -> DecsQ+makeFieldsNoPrefix = makeFieldOptics classUnderscoreNoPrefixFields++-- | Generate overloaded field accessors, using exactly the same names as the+-- underlying fields. Intended for use with the @NoFieldSelectors@ and+-- @DuplicateRecordFields@ language extensions.+--+-- As an example:+--+-- @+-- data Foo a  = Foo { x :: 'Int', y :: a }+-- newtype Bar = Bar { x :: 'Char' }+-- makeFieldsId ''Foo+-- makeFieldsId ''Bar+-- @+--+-- will create classes+--+-- @+-- class HasX s a | s -> a where+--   x :: Lens' s a+-- class HasY s a | s -> a where+--   y :: Lens' s a+-- @+--+-- together with instances+--+-- @+-- instance HasX (Foo a) Int+-- instance HasY (Foo a) a where+-- instance HasX Bar Char where+-- @+--+-- @+-- makeFieldsId = 'makeLensesWith' 'classIdFields'+-- @+makeFieldsId :: Name -> DecsQ+makeFieldsId = makeFieldOptics classIdFields++defaultFieldRules :: LensRules+defaultFieldRules = LensRules+  { _simpleLenses    = True+  , _generateSigs    = True+  , _generateClasses = True  -- classes will still be skipped if they already exist+  , _allowIsos       = False -- generating Isos would hinder field class reuse+  , _allowUpdates    = True+  , _lazyPatterns    = False+  , _recordSyntax    = False+  , _classyLenses    = const Nothing+  , _fieldToDef      = camelCaseNamer+  }+++-- Declaration quote stuff++declareWith :: (Dec -> Declare Dec) -> DecsQ -> DecsQ+declareWith fun = (runDeclare . traverseDataAndNewtype fun =<<)++-- | Monad for emitting top-level declarations as a side effect. We also track+-- the set of field class 'Name's that have been created and consult them to+-- avoid creating duplicate classes.++-- See #463 for more information.+type Declare = WriterT (Endo [Dec]) (StateT (Set Name) Q)++liftDeclare :: Q a -> Declare a+liftDeclare = lift . lift++runDeclare :: Declare [Dec] -> DecsQ+runDeclare dec = do+  (out, endo) <- evalStateT (runWriterT dec) Set.empty+  return $ out ++ appEndo endo []++emit :: [Dec] -> Declare ()+emit decs = tell $ Endo (decs++)++-- | Traverse each data, newtype, data instance or newtype instance+-- declaration.+traverseDataAndNewtype :: (Applicative f) => (Dec -> f Dec) -> [Dec] -> f [Dec]+traverseDataAndNewtype f = traverse go+  where+    go dec = case dec of+      DataD{} -> f dec+      NewtypeD{} -> f dec+      DataInstD{} -> f dec+      NewtypeInstD{} -> f dec++      -- Recurse into instance declarations because they main contain+      -- associated data family instances.+      InstanceD moverlap ctx inst body -> InstanceD moverlap ctx inst <$> traverse go body+      _ -> pure dec++stripFields :: Dec -> Dec+stripFields dec = case dec of+  DataD ctx tyName tyArgs kind cons derivings ->+    DataD ctx tyName tyArgs kind (map deRecord cons) derivings+  NewtypeD ctx tyName tyArgs kind con derivings ->+    NewtypeD ctx tyName tyArgs kind (deRecord con) derivings+  DataInstD ctx tyName tyArgs kind cons derivings ->+    DataInstD ctx tyName tyArgs kind (map deRecord cons) derivings+  NewtypeInstD ctx tyName tyArgs kind con derivings ->+    NewtypeInstD ctx tyName tyArgs kind (deRecord con) derivings+  _ -> dec++deRecord :: Con -> Con+deRecord con@NormalC{} = con+deRecord con@InfixC{} = con+deRecord (ForallC tyVars ctx con) = ForallC tyVars ctx $ deRecord con+deRecord (RecC conName fields) = NormalC conName (map dropFieldName fields)+deRecord con@GadtC{} = con+deRecord (RecGadtC ns fields retTy) = GadtC ns (map dropFieldName fields) retTy++dropFieldName :: VarBangType -> BangType+dropFieldName (_, str, typ) = (str, typ)
src/Control/Lens/Traversal.hs view
@@ -1,419 +1,1468 @@-{-# LANGUAGE Rank2Types #-}-{-# LANGUAGE LiberalTypeSynonyms #-}--------------------------------------------------------------------------------- |--- Module      :  Control.Lens.Traversal--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  Rank2Types------ A @'Traversal' a b c d@ is a generalization of 'traverse' from--- 'Traversable'. It allows you to traverse over a structure and change out--- its contents with monadic or applicative side-effects. Starting from------ @'traverse' :: ('Traversable' t, 'Applicative' f) => (c -> f d) -> t c -> f (t d)@,------ we monomorphize the contents and result to obtain------  > type Traversal a b c d = forall f. Applicative f => (c -> f d) -> a -> f b------ While a 'Traversal' isn't quite a 'Fold', it _can_ be used for 'Getting'--- like a 'Fold', because given a 'Monoid' @m@, we have an 'Applicative'--- for @('Const' m)@. Everything you know how to do with a 'Traversable'--- container, you can with with a 'Traversal', and here we provide--- combinators that generalize the usual 'Traversable' operations.------------------------------------------------------------------------------module Control.Lens.Traversal-  (-  -- * Lenses-    Traversal--  -- ** Lensing Traversals-  , element-  , elementOf--  -- * Traversing and Lensing-  , traverseOf, forOf, sequenceAOf-  , mapMOf, forMOf, sequenceOf-  , transposeOf-  , mapAccumLOf, mapAccumROf-  , scanr1Of, scanl1Of--  -- * Common Traversals-  , Traversable(traverse)-  , ignored-  , traverseLeft-  , traverseRight-  , both--  -- * Cloning Traversals-  , cloneTraversal-  , ReifiedTraversal(..)--  -- * Simple-  , SimpleTraversal-  , SimpleReifiedTraversal-  ) where--import Control.Applicative              as Applicative-import Control.Applicative.Backwards-import Control.Lens.Fold-import Control.Lens.Internal-import Control.Lens.Type-import Control.Monad.State.Class        as State-import Control.Monad.Trans.State.Lazy   as Lazy-import Data.Traversable---- $setup--- >>> import Control.Lens----------------------------------------------------------------------------------- Traversals----------------------------------------------------------------------------------- | A 'Traversal' can be used directly as a 'Control.Lens.Setter.Setter' or a 'Fold' (but not as a 'Lens') and provides--- the ability to both read and update multiple fields, subject to some relatively weak 'Traversal' laws.------ These have also been known as multilenses, but they have the signature and spirit of------ @'traverse' :: 'Traversable' f => 'Traversal' (f a) (f b) a b@------ and the more evocative name suggests their application.------ Most of the time the 'Traversal' you will want to use is just 'traverse', but you can also pass any--- 'Lens' or 'Control.Lens.Iso.Iso' as a 'Traversal', and composition of a 'Traversal' (or 'Lens' or 'Control.Lens.Iso.Iso') with a 'Traversal' (or 'Lens' or 'Control.Lens.Iso.Iso')--- using (.) forms a valid 'Traversal'.------ The laws for a Traversal @t@ follow from the laws for Traversable as stated in \"The Essence of the Iterator Pattern\".------ @--- t 'pure' ≡ 'pure'--- 'fmap' (t f) '.' t g ≡ 'Data.Functor.Compose.getCompose' '.' t ('Data.Functor.Compose.Compose' '.' 'fmap' f '.' g)--- @------ One consequence of this requirement is that a 'Traversal' needs to leave the same number of elements as a--- candidate for subsequent 'Traversal' that it started with. Another testament to the strength of these laws--- is that the caveat expressed in section 5.5 of the \"Essence of the Iterator Pattern\" about exotic--- 'Traversable' instances that 'traverse' the same entry multiple times was actually already ruled out by the--- second law in that same paper!-type Traversal a b c d = forall f. Applicative f => (c -> f d) -> a -> f b---- | @type SimpleTraversal = 'Simple' 'Traversal'@-type SimpleTraversal a b = Traversal a a b b------------------------------- Traversal Combinators------------------------------- |--- Map each element of a structure targeted by a Lens or Traversal,--- evaluate these actions from left to right, and collect the results.------ This function is only provided for consistency, 'id' is strictly more general.------ @'traverseOf' ≡ 'id'@------ This yields the obvious law:------ @'traverse' ≡ 'traverseOf' 'traverse'@------ @--- 'traverseOf' :: 'Control.Lens.Iso.Iso' a b c d       -> (c -> f d) -> a -> f b--- 'traverseOf' :: 'Lens' a b c d      -> (c -> f d) -> a -> f b--- 'traverseOf' :: 'Traversal' a b c d -> (c -> f d) -> a -> f b--- @-traverseOf :: LensLike f a b c d -> (c -> f d) -> a -> f b-traverseOf = id-{-# INLINE traverseOf #-}---- | A version of 'traverseOf' with the arguments flipped, such that:------ @'forOf' l ≡ 'flip' ('traverseOf' l)@------ @--- 'for' ≡ 'forOf' 'traverse'--- @------ This function is only provided for consistency, 'flip' is strictly more general.------ @--- 'forOf' ≡ 'flip'--- @------ @--- 'forOf' :: 'Control.Lens.Iso.Iso' a b c d -> a -> (c -> f d) -> f b--- 'forOf' :: 'Lens' a b c d -> a -> (c -> f d) -> f b--- 'forOf' :: 'Traversal' a b c d -> a -> (c -> f d) -> f b--- @-forOf :: LensLike f a b c d -> a -> (c -> f d) -> f b-forOf = flip-{-# INLINE forOf #-}---- |--- Evaluate each action in the structure from left to right, and collect--- the results.------ @--- 'sequenceA' ≡ 'sequenceAOf' 'traverse' ≡ 'traverse' 'id'--- 'sequenceAOf' l ≡ 'traverseOf' l id ≡ l id--- @------ @--- 'sequenceAOf' ::                  'Control.Lens.Iso.Iso' a b (f c) c       -> a -> f b--- 'sequenceAOf' ::                  'Lens' a b (f c) c      -> a -> f b--- 'sequenceAOf' :: 'Applicative' f => 'Traversal' a b (f c) c -> a -> f b--- @-sequenceAOf :: LensLike f a b (f c) c -> a -> f b-sequenceAOf l = l id-{-# INLINE sequenceAOf #-}---- | Map each element of a structure targeted by a lens to a monadic action,--- evaluate these actions from left to right, and collect the results.------ @'mapM' ≡ 'mapMOf' 'traverse'@------ @--- 'mapMOf' ::            'Control.Lens.Iso.Iso' a b c d       -> (c -> m d) -> a -> m b--- 'mapMOf' ::            'Lens' a b c d      -> (c -> m d) -> a -> m b--- 'mapMOf' :: 'Monad' m => 'Traversal' a b c d -> (c -> m d) -> a -> m b--- @-mapMOf :: LensLike (WrappedMonad m) a b c d -> (c -> m d) -> a -> m b-mapMOf l cmd = unwrapMonad . l (WrapMonad . cmd)-{-# INLINE mapMOf #-}---- | 'forMOf' is a flipped version of 'mapMOf', consistent with the definition of 'forM'.--- @--- 'forM' ≡ 'forMOf' 'traverse'--- 'forMOf' l ≡ 'flip' ('mapMOf' l)--- @------ @--- 'forMOf' ::            'Control.Lens.Iso.Iso' a b c d       -> a -> (c -> m d) -> m b--- 'forMOf' ::            'Lens' a b c d      -> a -> (c -> m d) -> m b--- 'forMOf' :: 'Monad' m => 'Traversal' a b c d -> a -> (c -> m d) -> m b--- @-forMOf :: LensLike (WrappedMonad m) a b c d -> a -> (c -> m d) -> m b-forMOf l a cmd = unwrapMonad (l (WrapMonad . cmd) a)-{-# INLINE forMOf #-}---- | Sequence the (monadic) effects targeted by a lens in a container from left to right.------ @--- 'sequence' ≡ 'sequenceOf' 'traverse'--- 'sequenceOf' l ≡ 'mapMOf' l id--- 'sequenceOf' l ≡ 'unwrapMonad' . l 'WrapMonad'--- @------ @--- 'sequenceOf' ::            'Control.Lens.Iso.Iso' a b (m c) c       -> a -> m b--- 'sequenceOf' ::            'Lens' a b (m c) c      -> a -> m b--- 'sequenceOf' :: 'Monad' m => 'Traversal' a b (m c) c -> a -> m b--- @-sequenceOf :: LensLike (WrappedMonad m) a b (m c) c -> a -> m b-sequenceOf l = unwrapMonad . l WrapMonad-{-# INLINE sequenceOf #-}---- | This generalizes 'Data.List.transpose' to an arbitrary 'Traversal'.------ Note: 'Data.List.transpose' handles ragged inputs more intelligently, but for non-ragged inputs:------ @'Data.List.transpose' ≡ 'transposeOf' 'traverse'@------ >>> transposeOf traverse [[1,2,3],[4,5,6]]--- [[1,4],[2,5],[3,6]]------ Since every 'Lens' is a 'Traversal', we can use this as a form of--- monadic strength as well:------ @'transposeOf' '_2' :: (b, [a]) -> [(b, a)]@-transposeOf :: LensLike ZipList a b [c] c -> a -> [b]-transposeOf l = getZipList . l ZipList-{-# INLINE transposeOf #-}---- | This generalizes 'Data.Traversable.mapAccumR' to an arbitrary 'Traversal'.------ @'mapAccumR' ≡ 'mapAccumROf' 'traverse'@------ 'mapAccumROf' accumulates state from right to left.------ @--- 'mapAccumROf' :: 'Control.Lens.Iso.Iso' a b c d       -> (s -> c -> (s, d)) -> s -> a -> (s, b)--- 'mapAccumROf' :: 'Lens' a b c d      -> (s -> c -> (s, d)) -> s -> a -> (s, b)--- 'mapAccumROf' :: 'Traversal' a b c d -> (s -> c -> (s, d)) -> s -> a -> (s, b)--- @-mapAccumROf :: LensLike (Lazy.State s) a b c d -> (s -> c -> (s, d)) -> s -> a -> (s, b)-mapAccumROf l f s0 a = swap (Lazy.runState (l (\c -> State.state (\s -> swap (f s c))) a) s0)-{-# INLINE mapAccumROf #-}---- | This generalizes 'Data.Traversable.mapAccumL' to an arbitrary 'Traversal'.------ @'mapAccumL' ≡ 'mapAccumLOf' 'traverse'@------ 'mapAccumLOf' accumulates state from left to right.------ @--- 'mapAccumLOf' :: 'Control.Lens.Iso.Iso' a b c d       -> (s -> c -> (s, d)) -> s -> a -> (s, b)--- 'mapAccumLOf' :: 'Lens' a b c d      -> (s -> c -> (s, d)) -> s -> a -> (s, b)--- 'mapAccumLOf' :: 'Traversal' a b c d -> (s -> c -> (s, d)) -> s -> a -> (s, b)--- @-mapAccumLOf :: LensLike (Backwards (Lazy.State s)) a b c d -> (s -> c -> (s, d)) -> s -> a -> (s, b)-mapAccumLOf = mapAccumROf . backwards-{-# INLINE mapAccumLOf #-}--swap :: (a,b) -> (b,a)-swap (a,b) = (b,a)-{-# INLINE swap #-}---- | This permits the use of 'scanr1' over an arbitrary 'Traversal' or 'Lens'.------ @'scanr1' ≡ 'scanr1Of' 'traverse'@------ @--- 'scanr1Of' :: 'Control.Lens.Iso.Iso' a b c c       -> (c -> c -> c) -> a -> b--- 'scanr1Of' :: 'Lens' a b c c      -> (c -> c -> c) -> a -> b--- 'scanr1Of' :: 'Traversal' a b c c -> (c -> c -> c) -> a -> b--- @-scanr1Of :: LensLike (Lazy.State (Maybe c)) a b c c -> (c -> c -> c) -> a -> b-scanr1Of l f = snd . mapAccumROf l step Nothing where-  step Nothing c  = (Just c, c)-  step (Just s) c = (Just r, r) where r = f c s-{-# INLINE scanr1Of #-}---- | This permits the use of 'scanl1' over an arbitrary 'Traversal' or 'Lens'.------ @'scanl1' ≡ 'scanl1Of' 'traverse'@------ @--- 'scanr1Of' :: 'Control.Lens.Iso.Iso' a b c c       -> (c -> c -> c) -> a -> b--- 'scanr1Of' :: 'Lens' a b c c      -> (c -> c -> c) -> a -> b--- 'scanr1Of' :: 'Traversal' a b c c -> (c -> c -> c) -> a -> b--- @-scanl1Of :: LensLike (Backwards (Lazy.State (Maybe c))) a b c c -> (c -> c -> c) -> a -> b-scanl1Of l f = snd . mapAccumLOf l step Nothing where-  step Nothing c  = (Just c, c)-  step (Just s) c = (Just r, r) where r = f s c-{-# INLINE scanl1Of #-}----------------------------------------------------------------------------------- Common Lenses----------------------------------------------------------------------------------- | A 'Lens' to 'Control.Lens.Getter.view'/'Control.Lens.Setter.set' the nth element 'elementOf' a 'Traversal', 'Lens' or 'Control.Lens.Iso.Iso'.------ Attempts to access beyond the range of the 'Traversal' will cause an error.------ >>> [[1],[3,4]]^.elementOf (traverse.traverse) 1--- 3-elementOf :: Functor f => LensLike (ElementOf f) a b c c -> Int -> LensLike f a b c c-elementOf l i f a = case getElementOf (l go a) 0 of-    Found _ fb    -> fb-    Searching _ _ -> error "elementOf: index out of range"-    NotFound e    -> error $ "elementOf: " ++ e-  where-    go c = ElementOf $ \j -> if i == j then Found (j + 1) (f c) else Searching (j + 1) c---- | Access the /nth/ element of a 'Traversable' container.------ Attempts to access beyond the range of the 'Traversal' will cause an error.------ @'element' ≡ 'elementOf' 'traverse'@-element :: Traversable t => Int -> Simple Lens (t a) a-element = elementOf traverse----------------------------------------------------------------------------------- Traversals----------------------------------------------------------------------------------- | This is the trivial empty traversal.------ @'ignored' :: 'Applicative' f => (c -> f d) -> a -> f a@------ @'ignored' ≡ 'const' 'pure'@-ignored :: Traversal a a c d-ignored _ = pure-{-# INLINE ignored #-}---- | Traverse both parts of a tuple with matching types.------ >>> both *~ 10 $ (1,2)--- (10,20)--- >>> over both length ("hello","world")--- (5,5)--- >>> ("hello","world")^.both--- "helloworld"-both :: Traversal (a,a) (b,b) a b-both f (a,a') = (,) <$> f a <*> f a'-{-# INLINE both #-}---- | A traversal for tweaking the left-hand value of an 'Either':------ >>> over traverseLeft (+1) (Left 2)--- Left 3--- >>> over traverseLeft (+1) (Right 2)--- Right 2--- >>> Right 42 ^.traverseLeft :: String--- ""--- >>> Left "hello" ^.traverseLeft--- "hello"------ @traverseLeft :: 'Applicative' f => (a -> f b) -> 'Either' a c -> f ('Either' b c)@-traverseLeft :: Traversal (Either a c) (Either b c) a b-traverseLeft f (Left a)  = Left <$> f a-traverseLeft _ (Right c) = pure $ Right c-{-# INLINE traverseLeft #-}---- | traverse the right-hand value of an 'Either':------ @'traverseRight' ≡ 'Data.Traversable.traverse'@------ Unfortunately the instance for--- @'Data.Traversable.Traversable' ('Either' c)@ is still missing from base,--- so this can't just be 'Data.Traversable.traverse'------ >>> over traverseRight (+1) (Left 2)--- Left 2--- >>> over traverseRight (+1) (Right 2)--- Right 3--- >>> Right "hello" ^.traverseRight--- "hello"--- >>> Left "hello" ^.traverseRight :: [Double]--- []------ @traverseRight :: 'Applicative' f => (a -> f b) -> 'Either' c a -> f ('Either' c a)@-traverseRight :: Traversal (Either c a) (Either c b) a b-traverseRight _ (Left c) = pure $ Left c-traverseRight f (Right a) = Right <$> f a-{-# INLINE traverseRight #-}------------------------------------------------------------------------------------ Cloning Traversals----------------------------------------------------------------------------------- | A 'Traversal' is completely characterized by its behavior on a 'Bazaar'.------ Cloning a 'Traversal' is one way to make sure you arent given--- something weaker, such as a 'Control.Lens.Traversal.Fold' and can be--- used as a way to pass around traversals that have to be monomorphic in @f@.------ Note: This only accepts a proper 'Traversal' (or 'Lens'). To clone a 'Lens'--- as such, use 'cloneLens'------ Note: It is usually better to 'ReifyTraversal' and use 'reflectTraversal'--- than to 'cloneTraversal'. The former can execute at full speed, while the--- latter needs to round trip through the 'Bazaar'.------ >>> let foo l a = (view (cloneTraversal l) a, set (cloneTraversal l) 10 a)--- >>> foo both ("hello","world")--- ("helloworld",(10,10))-cloneTraversal :: Applicative f => ((c -> Bazaar c d d) -> a -> Bazaar c d b) -> (c -> f d) -> a -> f b-cloneTraversal l f = bazaar f . l sell-{-# INLINE cloneTraversal #-}---- | A form of 'Traversal' that can be stored monomorphically in a container.-data ReifiedTraversal a b c d = ReifyTraversal { reflectTraversal :: Traversal a b c d }---- | @type SimpleReifiedTraversal = 'Simple' 'ReifiedTraversal'@-type SimpleReifiedTraversal a b = ReifiedTraversal a a b b+{-# LANGUAGE CPP #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE ConstraintKinds #-}++#include "lens-common.h"++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Traversal+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  Rank2Types+--+-- A @'Traversal' s t a b@ is a generalization of 'traverse' from+-- 'Traversable'. It allows you to 'traverse' over a structure and change out+-- its contents with monadic or 'Applicative' side-effects. Starting from+--+-- @+-- 'traverse' :: ('Traversable' t, 'Applicative' f) => (a -> f b) -> t a -> f (t b)+-- @+--+-- we monomorphize the contents and result to obtain+--+-- @+-- type 'Traversal' s t a b = forall f. 'Applicative' f => (a -> f b) -> s -> f t+-- @+--+-- A 'Traversal' can be used as a 'Fold'.+-- Any 'Traversal' can be used for 'Control.Lens.Getter.Getting' like a 'Fold',+-- because given a 'Data.Monoid.Monoid' @m@, we have an 'Applicative' for+-- @('Const' m)@. Everything you know how to do with a 'Traversable' container,+-- you can with a 'Traversal', and here we provide combinators that generalize+-- the usual 'Traversable' operations.+----------------------------------------------------------------------------+module Control.Lens.Traversal+  (+  -- * Traversals+    Traversal, Traversal'+  , Traversal1, Traversal1'+  , IndexedTraversal, IndexedTraversal'+  , IndexedTraversal1, IndexedTraversal1'+  , ATraversal, ATraversal'+  , ATraversal1, ATraversal1'+  , AnIndexedTraversal, AnIndexedTraversal'+  , AnIndexedTraversal1, AnIndexedTraversal1'+  , Traversing, Traversing'+  , Traversing1, Traversing1'++  -- * Traversing and Lensing+  , traversal+  , traverseOf, forOf, sequenceAOf+  , mapMOf, forMOf, sequenceOf+  , transposeOf+  , mapAccumLOf, mapAccumROf+  , scanr1Of, scanl1Of+  , failover, ifailover++  -- * Monomorphic Traversals+  , cloneTraversal+  , cloneIndexPreservingTraversal+  , cloneIndexedTraversal+  , cloneTraversal1+  , cloneIndexPreservingTraversal1+  , cloneIndexedTraversal1++  -- * Parts and Holes+  , partsOf, partsOf'+  , unsafePartsOf, unsafePartsOf'+  , holesOf, holes1Of+  , singular, unsafeSingular++  -- * Common Traversals+  , Traversable(traverse)+  , Traversable1(traverse1)+  , both, both1+  , beside+  , taking+  , dropping+  , failing+  , deepOf++  -- * Indexed Traversals++  -- ** Common+  , ignored+  , TraverseMin(..)+  , TraverseMax(..)+  , traversed+  , traversed1+  , traversed64+  , elementOf+  , element+  , elementsOf+  , elements++  -- ** Combinators+  , ipartsOf+  , ipartsOf'+  , iunsafePartsOf+  , iunsafePartsOf'+  , itraverseOf+  , iforOf+  , imapMOf+  , iforMOf+  , imapAccumROf+  , imapAccumLOf++  -- * Reflection+  , traverseBy+  , traverseByOf+  , sequenceBy+  , sequenceByOf++  -- * Implementation Details+  , Bazaar(..), Bazaar'+  , Bazaar1(..), Bazaar1'+  , loci+  , iloci++  -- * Fusion+  , confusing+  ) where++import Prelude ()++import Control.Applicative.Backwards+import qualified Control.Category as C+import Control.Comonad+import Control.Lens.Fold+import Control.Lens.Getter (Getting, IndexedGetting, getting)+import Control.Lens.Internal.Bazaar+import Control.Lens.Internal.Context+import Control.Lens.Internal.Fold+import Control.Lens.Internal.Indexed+import Control.Lens.Internal.Prelude+import Control.Lens.Lens+import Control.Lens.Setter (ASetter, AnIndexedSetter, isets, sets)+import Control.Lens.Type+import Control.Monad.Trans.State.Lazy+import Data.Bitraversable+import Data.CallStack+import Data.Functor.Apply+import Data.Functor.Day.Curried+import Data.Functor.Yoneda+import Data.Int+import qualified Data.IntMap as IntMap+import qualified Data.Map as Map+import Data.Map (Map)+import Data.Monoid (Any (..))+import Data.Sequence (Seq, mapWithIndex)+import Data.Vector as Vector (Vector, imap)+import Data.Profunctor.Rep (Representable (..))+import Data.Reflection+import Data.Semigroup.Traversable+import Data.Semigroup.Bitraversable+import Data.Tuple (swap)+import GHC.Exts (inline)++-- $setup+-- >>> :set -XNoOverloadedStrings -XFlexibleContexts+-- >>> import Data.Char (toUpper)+-- >>> import Control.Applicative+-- >>> import Control.Lens+-- >>> import Control.Lens.Internal.Context+-- >>> import Control.DeepSeq (NFData (..), force)+-- >>> import Control.Exception (evaluate,try,ErrorCall(..))+-- >>> import Data.Maybe (fromMaybe)+-- >>> import Data.List.NonEmpty (NonEmpty (..))+-- >>> import Debug.SimpleReflect.Vars+-- >>> import Data.Void+-- >>> import Data.List (sort)+-- >>> import System.Timeout (timeout)+-- >>> import qualified Data.List.NonEmpty as NonEmpty+-- >>> let timingOut :: NFData a => a -> IO a; timingOut = fmap (fromMaybe (error "timeout")) . timeout (5*10^6) . evaluate . force+-- >>> let firstAndThird :: Traversal (a, x, a) (b, x, b) a b; firstAndThird = traversal go where { go :: Applicative f => (a -> f b) -> (a, x, a) -> f (b, x, b); go focus (a, x, a') = liftA3 (,,) (focus a) (pure x) (focus a') }+-- >>> let selectNested :: Traversal (x, [a]) (x, [b]) a b; selectNested = traversal go where { go :: Applicative f => (a -> f b) -> (x, [a]) -> f (x, [b]); go focus (x, as) = liftA2 (,) (pure x) (traverse focus as) }++------------------------------------------------------------------------------+-- Traversals+------------------------------------------------------------------------------++-- | When you see this as an argument to a function, it expects a 'Traversal'.+type ATraversal s t a b = LensLike (Bazaar (->) a b) s t a b++-- | @+-- type 'ATraversal'' = 'Simple' 'ATraversal'+-- @+type ATraversal' s a = ATraversal s s a a+++-- | When you see this as an argument to a function, it expects a 'Traversal1'.+type ATraversal1 s t a b = LensLike (Bazaar1 (->) a b) s t a b++-- | @+-- type 'ATraversal1'' = 'Simple' 'ATraversal1'+-- @+type ATraversal1' s a = ATraversal1 s s a a++-- | When you see this as an argument to a function, it expects an 'IndexedTraversal'.+type AnIndexedTraversal i s t a b = Over (Indexed i) (Bazaar (Indexed i) a b) s t a b++-- | When you see this as an argument to a function, it expects an 'IndexedTraversal1'.+type AnIndexedTraversal1 i s t a b = Over (Indexed i) (Bazaar1 (Indexed i) a b) s t a b++-- | @+-- type 'AnIndexedTraversal'' = 'Simple' ('AnIndexedTraversal' i)+-- @+type AnIndexedTraversal' i s a = AnIndexedTraversal i s s a a++-- | @+-- type 'AnIndexedTraversal1'' = 'Simple' ('AnIndexedTraversal1' i)+-- @+type AnIndexedTraversal1' i s a = AnIndexedTraversal1 i s s a a+++-- | When you see this as an argument to a function, it expects+--+--  * to be indexed if @p@ is an instance of 'Indexed' i,+--+--  * to be unindexed if @p@ is @(->)@,+--+--  * a 'Traversal' if @f@ is 'Applicative',+--+--  * a 'Getter' if @f@ is only a 'Functor' and 'Data.Functor.Contravariant.Contravariant',+--+--  * a 'Lens' if @f@ is only a 'Functor',+--+--  * a 'Fold' if @f@ is 'Applicative' and 'Data.Functor.Contravariant.Contravariant'.+type Traversing p f s t a b = Over p (BazaarT p f a b) s t a b++type Traversing1 p f s t a b = Over p (BazaarT1 p f a b) s t a b++-- | @+-- type 'Traversing'' f = 'Simple' ('Traversing' f)+-- @+type Traversing' p f s a = Traversing p f s s a a+type Traversing1' p f s a = Traversing1 p f s s a a++--------------------------+-- Traversal Combinators+--------------------------++-- | Build a 'Traversal' by providing a function which specifies the elements you wish to+-- focus.+--+-- The caller provides a function of type:+--+-- @+-- Applicative f => (a -> f b) -> s -> f t+-- @+--+-- Which is a higher order function which accepts a "focusing function" and applies+-- it to all desired focuses within @s@, then constructs a @t@ using the Applicative+-- instance of @f@.+--+-- Only elements which are "focused" using the focusing function will be targeted by the+-- resulting traversal.+--+-- For example, we can explicitly write a traversal which targets the first and third elements+-- of a tuple like this:+--+-- @+-- firstAndThird :: Traversal (a, x, a) (b, x, b) a b+-- firstAndThird = traversal go+--   where+--     go :: Applicative f => (a -> f b) -> (a, x, a) -> f (b, x, b)+--     go focus (a, x, a') = liftA3 (,,) (focus a) (pure x) (focus a')+-- @+--+-- >>> (1,"two",3) & firstAndThird *~ 10+-- (10,"two",30)+--+-- >>> over firstAndThird length ("one",2,"three")+-- (3,2,5)+--+-- We can re-use existing 'Traversal's when writing new ones by passing our focusing function+-- along to them. This example re-uses 'traverse' to focus all elements in a list which is+-- embedded in a tuple. This traversal could also be written simply as @_2 . traverse@.+--+-- @+-- selectNested :: Traversal (x, [a]) (x, [b]) a b+-- selectNested = traversal go+--   where+--     go :: Applicative f => (a -> f b) -> (x, [a]) -> f (x, [b])+--     go focus (x, as) = liftA2 (,) (pure x) (traverse focus as)+-- @+--+-- >>> selectNested .~ "hello" $ (1,[2,3,4,5])+-- (1,["hello","hello","hello","hello"])+--+-- >>> (1,[2,3,4,5]) & selectNested *~ 3+-- (1,[6,9,12,15])+--+-- Note that the 'traversal' function actually just returns the same function you pass to+-- it. The function it accepts is in fact a valid traversal all on its own! The use of+-- 'traversal' does nothing except verify that the function it is passed matches the signature+-- of a valid traversal. One could remove the @traversal@ combinator from either of the last+-- two examples and use the definition of @go@ directly with no change in behaviour.+--+-- This function exists for consistency with the 'lens', 'prism' and 'iso' constructors+-- as well as to serve as a touchpoint for beginners who wish to construct their own+-- traversals but are uncertain how to do so.+traversal :: ((a -> f b) -> s -> f t) -> LensLike f s t a b+traversal = id+{-# INLINE traversal #-}++-- | Map each element of a structure targeted by a 'Lens' or 'Traversal',+-- evaluate these actions from left to right, and collect the results.+--+-- This function is only provided for consistency, 'id' is strictly more general.+--+-- >>> traverseOf each print (1,2,3)+-- 1+-- 2+-- 3+-- ((),(),())+--+-- @+-- 'traverseOf' ≡ 'id'+-- 'itraverseOf' l ≡ 'traverseOf' l '.' 'Indexed'+-- 'itraverseOf' 'itraversed' ≡ 'itraverse'+-- @+--+--+-- This yields the obvious law:+--+-- @+-- 'traverse' ≡ 'traverseOf' 'traverse'+-- @+--+-- @+-- 'traverseOf' :: 'Functor' f     => 'Iso' s t a b        -> (a -> f b) -> s -> f t+-- 'traverseOf' :: 'Functor' f     => 'Lens' s t a b       -> (a -> f b) -> s -> f t+-- 'traverseOf' :: 'Apply' f       => 'Traversal1' s t a b -> (a -> f b) -> s -> f t+-- 'traverseOf' :: 'Applicative' f => 'Traversal' s t a b  -> (a -> f b) -> s -> f t+-- @+traverseOf :: LensLike f s t a b -> (a -> f b) -> s -> f t+traverseOf = id+{-# INLINE traverseOf #-}++-- | A version of 'traverseOf' with the arguments flipped, such that:+--+-- >>> forOf each (1,2,3) print+-- 1+-- 2+-- 3+-- ((),(),())+--+-- This function is only provided for consistency, 'flip' is strictly more general.+--+-- @+-- 'forOf' ≡ 'flip'+-- 'forOf' ≡ 'flip' . 'traverseOf'+-- @+--+-- @+-- 'for' ≡ 'forOf' 'traverse'+-- 'Control.Lens.Indexed.ifor' l s ≡ 'for' l s '.' 'Indexed'+-- @+--+-- @+-- 'forOf' :: 'Functor' f => 'Iso' s t a b -> s -> (a -> f b) -> f t+-- 'forOf' :: 'Functor' f => 'Lens' s t a b -> s -> (a -> f b) -> f t+-- 'forOf' :: 'Applicative' f => 'Traversal' s t a b -> s -> (a -> f b) -> f t+-- @+forOf :: LensLike f s t a b -> s -> (a -> f b) -> f t+forOf = flip+{-# INLINE forOf #-}++-- | Evaluate each action in the structure from left to right, and collect+-- the results.+--+-- >>> sequenceAOf both ([1,2],[3,4])+-- [(1,3),(1,4),(2,3),(2,4)]+--+-- @+-- 'sequenceA' ≡ 'sequenceAOf' 'traverse' ≡ 'traverse' 'id'+-- 'sequenceAOf' l ≡ 'traverseOf' l 'id' ≡ l 'id'+-- @+--+-- @+-- 'sequenceAOf' :: 'Functor' f => 'Iso' s t (f b) b       -> s -> f t+-- 'sequenceAOf' :: 'Functor' f => 'Lens' s t (f b) b      -> s -> f t+-- 'sequenceAOf' :: 'Applicative' f => 'Traversal' s t (f b) b -> s -> f t+-- @+sequenceAOf :: LensLike f s t (f b) b -> s -> f t+sequenceAOf l = l id+{-# INLINE sequenceAOf #-}++-- | Map each element of a structure targeted by a 'Lens' to a monadic action,+-- evaluate these actions from left to right, and collect the results.+--+-- >>> mapMOf both (\x -> [x, x + 1]) (1,3)+-- [(1,3),(1,4),(2,3),(2,4)]+--+-- @+-- 'mapM' ≡ 'mapMOf' 'traverse'+-- 'imapMOf' l ≡ 'forM' l '.' 'Indexed'+-- @+--+-- @+-- 'mapMOf' :: 'Monad' m => 'Iso' s t a b       -> (a -> m b) -> s -> m t+-- 'mapMOf' :: 'Monad' m => 'Lens' s t a b      -> (a -> m b) -> s -> m t+-- 'mapMOf' :: 'Monad' m => 'Traversal' s t a b -> (a -> m b) -> s -> m t+-- @+mapMOf :: LensLike (WrappedMonad m) s t a b -> (a -> m b) -> s -> m t+mapMOf = coerce+{-# INLINE mapMOf #-}++-- | 'forMOf' is a flipped version of 'mapMOf', consistent with the definition of 'forM'.+--+-- >>> forMOf both (1,3) $ \x -> [x, x + 1]+-- [(1,3),(1,4),(2,3),(2,4)]+--+-- @+-- 'forM' ≡ 'forMOf' 'traverse'+-- 'forMOf' l ≡ 'flip' ('mapMOf' l)+-- 'iforMOf' l s ≡ 'forM' l s '.' 'Indexed'+-- @+--+-- @+-- 'forMOf' :: 'Monad' m => 'Iso' s t a b       -> s -> (a -> m b) -> m t+-- 'forMOf' :: 'Monad' m => 'Lens' s t a b      -> s -> (a -> m b) -> m t+-- 'forMOf' :: 'Monad' m => 'Traversal' s t a b -> s -> (a -> m b) -> m t+-- @+forMOf :: LensLike (WrappedMonad m) s t a b -> s -> (a -> m b) -> m t+forMOf l a cmd = unwrapMonad (l (WrapMonad #. cmd) a)+{-# INLINE forMOf #-}++-- | Sequence the (monadic) effects targeted by a 'Lens' in a container from left to right.+--+-- >>> sequenceOf each ([1,2],[3,4],[5,6])+-- [(1,3,5),(1,3,6),(1,4,5),(1,4,6),(2,3,5),(2,3,6),(2,4,5),(2,4,6)]+--+-- @+-- 'sequence' ≡ 'sequenceOf' 'traverse'+-- 'sequenceOf' l ≡ 'mapMOf' l 'id'+-- 'sequenceOf' l ≡ 'unwrapMonad' '.' l 'WrapMonad'+-- @+--+-- @+-- 'sequenceOf' :: 'Monad' m => 'Iso' s t (m b) b       -> s -> m t+-- 'sequenceOf' :: 'Monad' m => 'Lens' s t (m b) b      -> s -> m t+-- 'sequenceOf' :: 'Monad' m => 'Traversal' s t (m b) b -> s -> m t+-- @+sequenceOf :: LensLike (WrappedMonad m) s t (m b) b -> s -> m t+sequenceOf l = unwrapMonad #. l WrapMonad+{-# INLINE sequenceOf #-}++-- | This generalizes 'Data.List.transpose' to an arbitrary 'Traversal'.+--+-- Note: 'Data.List.transpose' handles ragged inputs more intelligently, but for non-ragged inputs:+--+-- >>> transposeOf traverse [[1,2,3],[4,5,6]]+-- [[1,4],[2,5],[3,6]]+--+-- @+-- 'Data.List.transpose' ≡ 'transposeOf' 'traverse'+-- @+--+-- Since every 'Lens' is a 'Traversal', we can use this as a form of+-- monadic strength as well:+--+-- @+-- 'transposeOf' 'Control.Lens.Tuple._2' :: (b, [a]) -> [(b, a)]+-- @+transposeOf :: LensLike ZipList s t [a] a -> s -> [t]+transposeOf l = getZipList #. l ZipList+{-# INLINE transposeOf #-}++-- | This generalizes 'Data.Traversable.mapAccumR' to an arbitrary 'Traversal'.+--+-- @+-- 'mapAccumR' ≡ 'mapAccumROf' 'traverse'+-- @+--+-- 'mapAccumROf' accumulates 'State' from right to left.+--+-- @+-- 'mapAccumROf' :: 'Iso' s t a b       -> (acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+-- 'mapAccumROf' :: 'Lens' s t a b      -> (acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+-- 'mapAccumROf' :: 'Traversal' s t a b -> (acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+-- @+--+-- @+-- 'mapAccumROf' :: 'LensLike' ('Backwards' ('State' acc)) s t a b -> (acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+-- @+mapAccumROf :: LensLike (Backwards (State acc)) s t a b -> (acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+mapAccumROf = mapAccumLOf . backwards+{-# INLINE mapAccumROf #-}++-- | This generalizes 'Data.Traversable.mapAccumL' to an arbitrary 'Traversal'.+--+-- @+-- 'mapAccumL' ≡ 'mapAccumLOf' 'traverse'+-- @+--+-- 'mapAccumLOf' accumulates 'State' from left to right.+--+-- @+-- 'mapAccumLOf' :: 'Iso' s t a b       -> (acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+-- 'mapAccumLOf' :: 'Lens' s t a b      -> (acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+-- 'mapAccumLOf' :: 'Traversal' s t a b -> (acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+-- @+--+-- @+-- 'mapAccumLOf' :: 'LensLike' ('State' acc) s t a b -> (acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+-- 'mapAccumLOf' l f acc0 s = 'swap' ('runState' (l (\a -> 'state' (\acc -> 'swap' (f acc a))) s) acc0)+-- @+--+mapAccumLOf :: LensLike (State acc) s t a b -> (acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+mapAccumLOf l f acc0 s = swap (runState (l g s) acc0) where+   g a = state $ \acc -> swap (f acc a)+-- This would be much cleaner if the argument order for the function was swapped.+{-# INLINE mapAccumLOf #-}++-- | This permits the use of 'scanr1' over an arbitrary 'Traversal' or 'Lens'.+--+-- @+-- 'scanr1' ≡ 'scanr1Of' 'traverse'+-- @+--+-- @+-- 'scanr1Of' :: 'Iso' s t a a       -> (a -> a -> a) -> s -> t+-- 'scanr1Of' :: 'Lens' s t a a      -> (a -> a -> a) -> s -> t+-- 'scanr1Of' :: 'Traversal' s t a a -> (a -> a -> a) -> s -> t+-- @+scanr1Of :: LensLike (Backwards (State (Maybe a))) s t a a -> (a -> a -> a) -> s -> t+scanr1Of l f = snd . mapAccumROf l step Nothing where+  step Nothing a  = (Just a, a)+  step (Just s) a = (Just r, r) where r = f a s+{-# INLINE scanr1Of #-}++-- | This permits the use of 'scanl1' over an arbitrary 'Traversal' or 'Lens'.+--+-- @+-- 'scanl1' ≡ 'scanl1Of' 'traverse'+-- @+--+-- @+-- 'scanl1Of' :: 'Iso' s t a a       -> (a -> a -> a) -> s -> t+-- 'scanl1Of' :: 'Lens' s t a a      -> (a -> a -> a) -> s -> t+-- 'scanl1Of' :: 'Traversal' s t a a -> (a -> a -> a) -> s -> t+-- @+scanl1Of :: LensLike (State (Maybe a)) s t a a -> (a -> a -> a) -> s -> t+scanl1Of l f = snd . mapAccumLOf l step Nothing where+  step Nothing a  = (Just a, a)+  step (Just s) a = (Just r, r) where r = f s a+{-# INLINE scanl1Of #-}++-- | This 'Traversal' allows you to 'traverse' the individual stores in a 'Bazaar'.+loci :: Traversal (Bazaar (->) a c s) (Bazaar (->) b c s) a b+loci f w = getCompose (runBazaar w (Compose #. fmap sell . f))+{-# INLINE loci #-}++-- | This 'IndexedTraversal' allows you to 'traverse' the individual stores in+-- a 'Bazaar' with access to their indices.+iloci :: IndexedTraversal i (Bazaar (Indexed i) a c s) (Bazaar (Indexed i) b c s) a b+iloci f w = getCompose (runBazaar w (Compose #. Indexed (\i -> fmap (indexed sell i) . indexed f i)))+{-# INLINE iloci #-}++-------------------------------------------------------------------------------+-- Parts+-------------------------------------------------------------------------------++-- | 'partsOf' turns a 'Traversal' into a 'Lens' that resembles an early version of the 'Data.Data.Lens.uniplate' (or 'Data.Data.Lens.biplate') type.+--+-- /Note:/ You should really try to maintain the invariant of the number of children in the list.+--+-- >>> (a,b,c) & partsOf each .~ [x,y,z]+-- (x,y,z)+--+-- Any extras will be lost. If you do not supply enough, then the remainder will come from the original structure.+--+-- >>> (a,b,c) & partsOf each .~ [w,x,y,z]+-- (w,x,y)+--+-- >>> (a,b,c) & partsOf each .~ [x,y]+-- (x,y,c)+--+-- >>> ('b', 'a', 'd', 'c') & partsOf each %~ sort+-- ('a','b','c','d')+--+-- So technically, this is only a 'Lens' if you do not change the number of results it returns.+--+-- When applied to a 'Fold' the result is merely a 'Getter'.+--+-- @+-- 'partsOf' :: 'Iso'' s a       -> 'Lens'' s [a]+-- 'partsOf' :: 'Lens'' s a      -> 'Lens'' s [a]+-- 'partsOf' :: 'Traversal'' s a -> 'Lens'' s [a]+-- 'partsOf' :: 'Fold' s a       -> 'Getter' s [a]+-- 'partsOf' :: 'Getter' s a     -> 'Getter' s [a]+-- @+partsOf :: Functor f => Traversing (->) f s t a a -> LensLike f s t [a] [a]+partsOf l f s = outs b <$> f (ins b) where b = l sell s+{-# INLINE partsOf #-}++-- | An indexed version of 'partsOf' that receives the entire list of indices as its index.+ipartsOf :: forall i p f s t a. (Indexable [i] p, Functor f) => Traversing (Indexed i) f s t a a -> Over p f s t [a] [a]+ipartsOf l = conjoined+  (\f s -> let b = inline l sell s                            in outs b <$> f (wins b))+  (\f s -> let b = inline l sell s; (is, as) = unzip (pins b) in outs b <$> indexed f (is :: [i]) as)+{-# INLINE ipartsOf #-}++-- | A type-restricted version of 'partsOf' that can only be used with a 'Traversal'.+partsOf' :: ATraversal s t a a -> Lens s t [a] [a]+partsOf' l f s = outs b <$> f (ins b) where b = l sell s+{-# INLINE partsOf' #-}++-- | A type-restricted version of 'ipartsOf' that can only be used with an 'IndexedTraversal'.+ipartsOf' :: forall i p f s t a. (Indexable [i] p, Functor f) => Over (Indexed i) (Bazaar' (Indexed i) a) s t a a -> Over p f s t [a] [a]+ipartsOf' l = conjoined+  (\f s -> let b = inline l sell s                            in outs b <$> f (wins b))+  (\f s -> let b = inline l sell s; (is, as) = unzip (pins b) in outs b <$> indexed f (is :: [i]) as)+{-# INLINE ipartsOf' #-}++-- | 'unsafePartsOf' turns a 'Traversal' into a 'Data.Data.Lens.uniplate' (or 'Data.Data.Lens.biplate') family.+--+-- If you do not need the types of @s@ and @t@ to be different, it is recommended that+-- you use 'partsOf'.+--+-- It is generally safer to traverse with the 'Bazaar' rather than use this+-- combinator. However, it is sometimes convenient.+--+-- This is unsafe because if you don't supply at least as many @b@'s as you were+-- given @a@'s, then the reconstruction of @t@ /will/ result in an error!+--+-- When applied to a 'Fold' the result is merely a 'Getter' (and becomes safe).+--+-- @+-- 'unsafePartsOf' :: 'Iso' s t a b       -> 'Lens' s t [a] [b]+-- 'unsafePartsOf' :: 'Lens' s t a b      -> 'Lens' s t [a] [b]+-- 'unsafePartsOf' :: 'Traversal' s t a b -> 'Lens' s t [a] [b]+-- 'unsafePartsOf' :: 'Fold' s a          -> 'Getter' s [a]+-- 'unsafePartsOf' :: 'Getter' s a        -> 'Getter' s [a]+-- @+unsafePartsOf :: Functor f => Traversing (->) f s t a b -> LensLike f s t [a] [b]+unsafePartsOf l f s = unsafeOuts b <$> f (ins b) where b = l sell s+{-# INLINE unsafePartsOf #-}++-- | An indexed version of 'unsafePartsOf' that receives the entire list of indices as its index.+iunsafePartsOf :: forall i p f s t a b. (Indexable [i] p, Functor f) => Traversing (Indexed i) f s t a b -> Over p f s t [a] [b]+iunsafePartsOf l = conjoined+  (\f s -> let b = inline l sell s                           in unsafeOuts b <$> f (wins b))+  (\f s -> let b = inline l sell s; (is,as) = unzip (pins b) in unsafeOuts b <$> indexed f (is :: [i]) as)+{-# INLINE iunsafePartsOf #-}++unsafePartsOf' :: ATraversal s t a b -> Lens s t [a] [b]+unsafePartsOf' l f s = unsafeOuts b <$> f (ins b) where b = l sell s+{-# INLINE unsafePartsOf' #-}++iunsafePartsOf' :: forall i s t a b. Over (Indexed i) (Bazaar (Indexed i) a b) s t a b -> IndexedLens [i] s t [a] [b]+iunsafePartsOf' l = conjoined+  (\f s -> let b = inline l sell s                            in unsafeOuts b <$> f (wins b))+  (\f s -> let b = inline l sell s; (is, as) = unzip (pins b) in unsafeOuts b <$> indexed f (is :: [i]) as)+{-# INLINE iunsafePartsOf' #-}+++-- | This converts a 'Traversal' that you \"know\" will target one or more elements to a 'Lens'. It can+-- also be used to transform a non-empty 'Fold' into a 'Getter'.+--+-- The resulting 'Lens' or 'Getter' will be partial if the supplied 'Traversal' returns+-- no results.+--+-- >>> [1,2,3] ^. singular _head+-- 1+--+-- >>> Left (ErrorCall "singular: empty traversal") <- try (evaluate ([] ^. singular _head)) :: IO (Either ErrorCall ())+--+-- >>> Left 4 ^. singular _Left+-- 4+--+-- >>> [1..10] ^. singular (ix 7)+-- 8+--+-- >>> [] & singular traverse .~ 0+-- []+--+-- @+-- 'singular' :: 'Traversal' s t a a          -> 'Lens' s t a a+-- 'singular' :: 'Fold' s a                   -> 'Getter' s a+-- 'singular' :: 'IndexedTraversal' i s t a a -> 'IndexedLens' i s t a a+-- 'singular' :: 'IndexedFold' i s a          -> 'IndexedGetter' i s a+-- @+singular :: (HasCallStack, Conjoined p, Functor f)+         => Traversing p f s t a a+         -> Over p f s t a a+singular l = conjoined+  (\afb s -> let b = l sell s in case ins b of+    (w:ws) -> unsafeOuts b . (:ws) <$> afb w+    []     -> unsafeOuts b . return <$> afb (error "singular: empty traversal"))+  (\pafb s -> let b = l sell s in case pins b of+    (w:ws) -> unsafeOuts b . (:map extract ws) <$> cosieve pafb w+    []     -> unsafeOuts b . return                    <$> cosieve pafb (error "singular: empty traversal"))+{-# INLINE singular #-}++-- | This converts a 'Traversal' that you \"know\" will target only one element to a 'Lens'. It can also be+-- used to transform a 'Fold' into a 'Getter'.+--+-- The resulting 'Lens' or 'Getter' will be partial if the 'Traversal' targets nothing+-- or more than one element.+--+-- >>> Left (ErrorCall "unsafeSingular: empty traversal") <- try (evaluate ([] & unsafeSingular traverse .~ 0)) :: IO (Either ErrorCall [Integer])+--+-- @+-- 'unsafeSingular' :: 'Traversal' s t a b          -> 'Lens' s t a b+-- 'unsafeSingular' :: 'Fold' s a                   -> 'Getter' s a+-- 'unsafeSingular' :: 'IndexedTraversal' i s t a b -> 'IndexedLens' i s t a b+-- 'unsafeSingular' :: 'IndexedFold' i s a          -> 'IndexedGetter' i s a+-- @+unsafeSingular :: (HasCallStack, Conjoined p, Functor f)+               => Traversing p f s t a b+               -> Over p f s t a b+unsafeSingular l = conjoined+  (\afb s -> let b = inline l sell s in case ins b of+    [w] -> unsafeOuts b . return <$> afb w+    []  -> error "unsafeSingular: empty traversal"+    _   -> error "unsafeSingular: traversing multiple results")+  (\pafb s -> let b = inline l sell s in case pins b of+    [w] -> unsafeOuts b . return <$> cosieve pafb w+    []  -> error "unsafeSingular: empty traversal"+    _   -> error "unsafeSingular: traversing multiple results")+{-# INLINE unsafeSingular #-}++------------------------------------------------------------------------------+-- Internal functions used by 'partsOf', etc.+------------------------------------------------------------------------------++ins :: Bizarre (->) w => w a b t -> [a]+ins = toListOf (getting bazaar)+{-# INLINE ins #-}++wins :: (Bizarre p w, Corepresentable p, Comonad (Corep p)) => w a b t -> [a]+wins = getConst #. bazaar (cotabulate $ \ra -> Const [extract ra])+{-# INLINE wins #-}++pins :: (Bizarre p w, Corepresentable p) => w a b t -> [Corep p a]+pins = getConst #. bazaar (cotabulate $ \ra -> Const [ra])+{-# INLINE pins #-}++parr :: (Profunctor p, C.Category p) => (a -> b) -> p a b+parr f = lmap f C.id+{-# INLINE parr #-}++outs :: (Bizarre p w, C.Category p) => w a a t -> [a] -> t+outs = evalState `rmap` bazaar (parr (state . unconsWithDefault))+{-# INLINE outs #-}++unsafeOuts :: (Bizarre p w, Corepresentable p) => w a b t -> [b] -> t+unsafeOuts = evalState `rmap` bazaar (cotabulate (\_ -> state (unconsWithDefault fakeVal)))+  where fakeVal = error "unsafePartsOf': not enough elements were supplied"+{-# INLINE unsafeOuts #-}++unconsWithDefault :: a -> [a] -> (a,[a])+unconsWithDefault d []     = (d,[])+unconsWithDefault _ (x:xs) = (x,xs)+{-# INLINE unconsWithDefault #-}+++-------------------------------------------------------------------------------+-- Holes+-------------------------------------------------------------------------------++-- | The one-level version of 'Control.Lens.Plated.contextsOf'. This extracts a+-- list of the immediate children according to a given 'Traversal' as editable+-- contexts.+--+-- Given a context you can use 'Control.Comonad.Store.Class.pos' to see the+-- values, 'Control.Comonad.Store.Class.peek' at what the structure would be+-- like with an edited result, or simply 'extract' the original structure.+--+-- @+-- propChildren l x = 'toListOf' l x '==' 'map' 'Control.Comonad.Store.Class.pos' ('holesOf' l x)+-- propId l x = 'all' ('==' x) ['extract' w | w <- 'holesOf' l x]+-- @+--+-- @+-- 'holesOf' :: 'Iso'' s a                -> s -> ['Pretext'' (->) a s]+-- 'holesOf' :: 'Lens'' s a               -> s -> ['Pretext'' (->) a s]+-- 'holesOf' :: 'Traversal'' s a          -> s -> ['Pretext'' (->) a s]+-- 'holesOf' :: 'IndexedLens'' i s a      -> s -> ['Pretext'' ('Indexed' i) a s]+-- 'holesOf' :: 'IndexedTraversal'' i s a -> s -> ['Pretext'' ('Indexed' i) a s]+-- @+holesOf :: Conjoined p+        => Over p (Bazaar p a a) s t a a -> s -> [Pretext p a a t]+holesOf f xs = flip appEndo [] . fst $+  runHoles (runBazaar (f sell xs) (cotabulate holeInOne)) id+{-# INLINE holesOf #-}++holeInOne :: (Corepresentable p, Comonad (Corep p))+          => Corep p a -> Holes t (Endo [Pretext p a a t]) a+holeInOne x = Holes $ \xt ->+    ( Endo (fmap xt (cosieve sell x) :)+    , extract x)+{-# INLINABLE holeInOne #-}++-- | The non-empty version of 'holesOf'.+-- This extract a non-empty list of immediate children according to a given+-- 'Traversal1' as editable contexts.+--+-- >>> let head1 f s = runPretext (NonEmpty.head $ holes1Of traversed1 s) f+-- >>> ('a' :| "bc") ^. head1+-- 'a'+--+-- >>> ('a' :| "bc") & head1 %~ toUpper+-- 'A' :| "bc"+--+-- @+-- 'holes1Of' :: 'Iso'' s a                 -> s -> 'NonEmpty' ('Pretext'' (->) a s)+-- 'holes1Of' :: 'Lens'' s a                -> s -> 'NonEmpty' ('Pretext'' (->) a s)+-- 'holes1Of' :: 'Traversal1'' s a          -> s -> 'NonEmpty' ('Pretext'' (->) a s)+-- 'holes1Of' :: 'IndexedLens'' i s a       -> s -> 'NonEmpty' ('Pretext'' ('Indexed' i) a s)+-- 'holes1Of' :: 'IndexedTraversal1'' i s a -> s -> 'NonEmpty' ('Pretext'' ('Indexed' i) a s)+-- @+holes1Of :: Conjoined p+         => Over p (Bazaar1 p a a) s t a a -> s -> NonEmpty (Pretext p a a t)+holes1Of f xs = flip getNonEmptyDList [] . fst $+  runHoles (runBazaar1 (f sell xs) (cotabulate holeInOne1)) id+{-# INLINE holes1Of #-}++holeInOne1 :: forall p a t. (Corepresentable p, C.Category p)+          => Corep p a -> Holes t (NonEmptyDList (Pretext p a a t)) a+holeInOne1 x = Holes $ \xt ->+    ( NonEmptyDList (fmap xt (cosieve sell x) :|)+    , cosieve (C.id :: p a a) x)++-- We are very careful to share as much structure as possible among+-- the results (in the common case where the traversal allows for such).+-- Note in particular the recursive knot in the implementation of <*>+-- for Holes. This sharing magic was inspired by Noah "Rampion" Easterly's+-- implementation of a related holes function: see+-- https://stackoverflow.com/a/49001904/1477667. The Holes type is+-- inspired by Roman Cheplyaka's answer to that same question.++newtype Holes t m x = Holes { runHoles :: (x -> t) -> (m, x) }++instance Functor (Holes t m) where+  fmap f xs = Holes $ \xt ->+    let+      (qf, qv) = runHoles xs (xt . f)+    in (qf, f qv)++instance Semigroup m => Apply (Holes t m) where+  fs <.> xs = Holes $ \xt ->+    let+     (pf, pv) = runHoles fs (xt . ($ qv))+     (qf, qv) = runHoles xs (xt . pv)+    in (pf <> qf, pv qv)++instance Monoid m => Applicative (Holes t m) where+  pure x = Holes $ \_ -> (mempty, x)++  fs <*> xs = Holes $ \xt ->+    let+     (pf, pv) = runHoles fs (xt . ($ qv))+     (qf, qv) = runHoles xs (xt . pv)+    in (pf `mappend` qf, pv qv)++#if MIN_VERSION_base(4,10,0)+  liftA2 f xs ys = Holes $ \xt ->+    let+      (pf, pv) = runHoles xs (xt . flip f qv)+      (qf, qv) = runHoles ys (xt . f pv)+    in (pf `mappend` qf, f pv qv)+#endif+++------------------------------------------------------------------------------+-- Traversals+------------------------------------------------------------------------------++-- | Traverse both parts of a 'Bitraversable' container with matching types.+--+-- Usually that type will be a pair. Use 'Control.Lens.Each.each' to traverse+-- the elements of arbitrary homogeneous tuples.+--+-- >>> (1,2) & both *~ 10+-- (10,20)+--+-- >>> over both length ("hello","world")+-- (5,5)+--+-- >>> ("hello","world")^.both+-- "helloworld"+--+-- @+-- 'both' :: 'Traversal' (a, a)       (b, b)       a b+-- 'both' :: 'Traversal' ('Either' a a) ('Either' b b) a b+-- @+both :: Bitraversable r => Traversal (r a a) (r b b) a b+both f = bitraverse f f+{-# INLINE both #-}++-- | Traverse both parts of a 'Bitraversable1' container with matching types.+--+-- Usually that type will be a pair.+--+-- @+-- 'both1' :: 'Traversal1' (a, a)       (b, b)       a b+-- 'both1' :: 'Traversal1' ('Either' a a) ('Either' b b) a b+-- @+both1 :: Bitraversable1 r => Traversal1 (r a a) (r b b) a b+both1 f = bitraverse1 f f+{-# INLINE both1 #-}++-- | Apply a different 'Traversal' or 'Fold' to each side of a 'Bitraversable' container.+--+-- @+-- 'beside' :: 'Traversal' s t a b                -> 'Traversal' s' t' a b                -> 'Traversal' (r s s') (r t t') a b+-- 'beside' :: 'IndexedTraversal' i s t a b       -> 'IndexedTraversal' i s' t' a b       -> 'IndexedTraversal' i (r s s') (r t t') a b+-- 'beside' :: 'IndexPreservingTraversal' s t a b -> 'IndexPreservingTraversal' s' t' a b -> 'IndexPreservingTraversal' (r s s') (r t t') a b+-- @+--+-- @+-- 'beside' :: 'Traversal' s t a b                -> 'Traversal' s' t' a b                -> 'Traversal' (s,s') (t,t') a b+-- 'beside' :: 'Lens' s t a b                     -> 'Lens' s' t' a b                     -> 'Traversal' (s,s') (t,t') a b+-- 'beside' :: 'Fold' s a                         -> 'Fold' s' a                          -> 'Fold' (s,s') a+-- 'beside' :: 'Getter' s a                       -> 'Getter' s' a                        -> 'Fold' (s,s') a+-- @+--+-- @+-- 'beside' :: 'IndexedTraversal' i s t a b       -> 'IndexedTraversal' i s' t' a b       -> 'IndexedTraversal' i (s,s') (t,t') a b+-- 'beside' :: 'IndexedLens' i s t a b            -> 'IndexedLens' i s' t' a b            -> 'IndexedTraversal' i (s,s') (t,t') a b+-- 'beside' :: 'IndexedFold' i s a                -> 'IndexedFold' i s' a                 -> 'IndexedFold' i (s,s') a+-- 'beside' :: 'IndexedGetter' i s a              -> 'IndexedGetter' i s' a               -> 'IndexedFold' i (s,s') a+-- @+--+-- @+-- 'beside' :: 'IndexPreservingTraversal' s t a b -> 'IndexPreservingTraversal' s' t' a b -> 'IndexPreservingTraversal' (s,s') (t,t') a b+-- 'beside' :: 'IndexPreservingLens' s t a b      -> 'IndexPreservingLens' s' t' a b      -> 'IndexPreservingTraversal' (s,s') (t,t') a b+-- 'beside' :: 'IndexPreservingFold' s a          -> 'IndexPreservingFold' s' a           -> 'IndexPreservingFold' (s,s') a+-- 'beside' :: 'IndexPreservingGetter' s a        -> 'IndexPreservingGetter' s' a         -> 'IndexPreservingFold' (s,s') a+-- @+--+-- >>> ("hello",["world","!!!"])^..beside id traverse+-- ["hello","world","!!!"]+beside :: (Representable q, Applicative (Rep q), Applicative f, Bitraversable r)+       => Optical p q f s t a b+       -> Optical p q f s' t' a b+       -> Optical p q f (r s s') (r t t') a b+beside l r f = tabulate $ getCompose #. bitraverse (Compose #. sieve (l f)) (Compose #. sieve (r f))+{-# INLINE beside #-}++-- | Visit the first /n/ targets of a 'Traversal', 'Fold', 'Getter' or 'Lens'.+--+-- >>> [("hello","world"),("!!!","!!!")]^.. taking 2 (traverse.both)+-- ["hello","world"]+--+-- >>> timingOut $ [1..] ^.. taking 3 traverse+-- [1,2,3]+--+-- >>> over (taking 5 traverse) succ "hello world"+-- "ifmmp world"+--+-- @+-- 'taking' :: 'Int' -> 'Traversal'' s a                   -> 'Traversal'' s a+-- 'taking' :: 'Int' -> 'Lens'' s a                        -> 'Traversal'' s a+-- 'taking' :: 'Int' -> 'Iso'' s a                         -> 'Traversal'' s a+-- 'taking' :: 'Int' -> 'Prism'' s a                       -> 'Traversal'' s a+-- 'taking' :: 'Int' -> 'Getter' s a                       -> 'Fold' s a+-- 'taking' :: 'Int' -> 'Fold' s a                         -> 'Fold' s a+-- 'taking' :: 'Int' -> 'IndexedTraversal'' i s a          -> 'IndexedTraversal'' i s a+-- 'taking' :: 'Int' -> 'IndexedLens'' i s a               -> 'IndexedTraversal'' i s a+-- 'taking' :: 'Int' -> 'IndexedGetter' i s a              -> 'IndexedFold' i s a+-- 'taking' :: 'Int' -> 'IndexedFold' i s a                -> 'IndexedFold' i s a+-- @+taking :: (Conjoined p, Applicative f)+        => Int+       -> Traversing p f s t a a+       -> Over p f s t a a+taking n l = conjoined+  (\ afb s  -> let b = inline l sell s in outs b <$> traverse afb          (take n $ ins b))+  (\ pafb s -> let b = inline l sell s in outs b <$> traverse (cosieve pafb) (take n $ pins b))+{-# INLINE taking #-}++-- | Visit all but the first /n/ targets of a 'Traversal', 'Fold', 'Getter' or 'Lens'.+--+-- >>> ("hello","world") ^? dropping 1 both+-- Just "world"+--+-- Dropping works on infinite traversals as well:+--+-- >>> [1..] ^? dropping 1 folded+-- Just 2+--+-- @+-- 'dropping' :: 'Int' -> 'Traversal'' s a                   -> 'Traversal'' s a+-- 'dropping' :: 'Int' -> 'Lens'' s a                        -> 'Traversal'' s a+-- 'dropping' :: 'Int' -> 'Iso'' s a                         -> 'Traversal'' s a+-- 'dropping' :: 'Int' -> 'Prism'' s a                       -> 'Traversal'' s a+-- 'dropping' :: 'Int' -> 'Getter' s a                       -> 'Fold' s a+-- 'dropping' :: 'Int' -> 'Fold' s a                         -> 'Fold' s a+-- 'dropping' :: 'Int' -> 'IndexedTraversal'' i s a          -> 'IndexedTraversal'' i s a+-- 'dropping' :: 'Int' -> 'IndexedLens'' i s a               -> 'IndexedTraversal'' i s a+-- 'dropping' :: 'Int' -> 'IndexedGetter' i s a              -> 'IndexedFold' i s a+-- 'dropping' :: 'Int' -> 'IndexedFold' i s a                -> 'IndexedFold' i s a+-- @+dropping :: (Conjoined p, Applicative f) => Int -> Over p (Indexing f) s t a a -> Over p f s t a a+dropping n l pafb s = snd $ runIndexing (l paifb s) 0 where+  paifb = cotabulate $ \wa -> Indexing $ \i -> let i' = i + 1 in i' `seq` (i', if i < n then pure (extract wa) else cosieve pafb wa)+{-# INLINE dropping #-}++------------------------------------------------------------------------------+-- Cloning Traversals+------------------------------------------------------------------------------++-- | A 'Traversal' is completely characterized by its behavior on a 'Bazaar'.+--+-- Cloning a 'Traversal' is one way to make sure you aren't given+-- something weaker, such as a 'Fold' and can be+-- used as a way to pass around traversals that have to be monomorphic in @f@.+--+-- Note: This only accepts a proper 'Traversal' (or 'Lens'). To clone a 'Lens'+-- as such, use 'Control.Lens.Lens.cloneLens'.+--+-- Note: It is usually better to use 'Control.Lens.Reified.ReifiedTraversal' and+-- 'Control.Lens.Reified.runTraversal' than to 'cloneTraversal'. The+-- former can execute at full speed, while the latter needs to round trip through+-- the 'Bazaar'.+--+-- >>> let foo l a = (view (getting (cloneTraversal l)) a, set (cloneTraversal l) 10 a)+-- >>> foo both ("hello","world")+-- ("helloworld",(10,10))+--+-- @+-- 'cloneTraversal' :: 'LensLike' ('Bazaar' (->) a b) s t a b -> 'Traversal' s t a b+-- @+cloneTraversal :: ATraversal s t a b -> Traversal s t a b+cloneTraversal l f = bazaar f . l sell+{-# INLINE cloneTraversal #-}++-- | Clone a 'Traversal' yielding an 'IndexPreservingTraversal' that passes through+-- whatever index it is composed with.+cloneIndexPreservingTraversal :: ATraversal s t a b -> IndexPreservingTraversal s t a b+cloneIndexPreservingTraversal l pafb = cotabulate $ \ws -> runBazaar (l sell (extract ws)) $ \a -> cosieve pafb (a <$ ws)+{-# INLINE cloneIndexPreservingTraversal #-}++-- | Clone an 'IndexedTraversal' yielding an 'IndexedTraversal' with the same index.+cloneIndexedTraversal :: AnIndexedTraversal i s t a b -> IndexedTraversal i s t a b+cloneIndexedTraversal l f = bazaar (Indexed (indexed f)) . l sell+{-# INLINE cloneIndexedTraversal #-}++-- | A 'Traversal1' is completely characterized by its behavior on a 'Bazaar1'.+cloneTraversal1 :: ATraversal1 s t a b -> Traversal1 s t a b+cloneTraversal1 l f = bazaar1 f . l sell+{-# INLINE cloneTraversal1 #-}++-- | Clone a 'Traversal1' yielding an 'IndexPreservingTraversal1' that passes through+-- whatever index it is composed with.+cloneIndexPreservingTraversal1 :: ATraversal1 s t a b -> IndexPreservingTraversal1 s t a b+cloneIndexPreservingTraversal1 l pafb = cotabulate $ \ws -> runBazaar1 (l sell (extract ws)) $ \a -> cosieve pafb (a <$ ws)+{-# INLINE cloneIndexPreservingTraversal1 #-}++-- | Clone an 'IndexedTraversal1' yielding an 'IndexedTraversal1' with the same index.+cloneIndexedTraversal1 :: AnIndexedTraversal1 i s t a b -> IndexedTraversal1 i s t a b+cloneIndexedTraversal1 l f = bazaar1 (Indexed (indexed f)) . l sell+{-# INLINE cloneIndexedTraversal1 #-}++------------------------------------------------------------------------------+-- Indexed Traversals+------------------------------------------------------------------------------++-- | Traversal with an index.+--+-- /NB:/ When you don't need access to the index then you can just apply your 'IndexedTraversal'+-- directly as a function!+--+-- @+-- 'itraverseOf' ≡ 'Control.Lens.Indexed.withIndex'+-- 'Control.Lens.Traversal.traverseOf' l = 'itraverseOf' l '.' 'const' = 'id'+-- @+--+-- @+-- 'itraverseOf' :: 'Functor' f     => 'IndexedLens' i s t a b       -> (i -> a -> f b) -> s -> f t+-- 'itraverseOf' :: 'Applicative' f => 'IndexedTraversal' i s t a b  -> (i -> a -> f b) -> s -> f t+-- 'itraverseOf' :: 'Apply' f       => 'IndexedTraversal1' i s t a b -> (i -> a -> f b) -> s -> f t+-- @+itraverseOf :: (Indexed i a (f b) -> s -> f t) -> (i -> a -> f b) -> s -> f t+itraverseOf l = l .# Indexed+{-# INLINE itraverseOf #-}++-- | Traverse with an index (and the arguments flipped).+--+-- @+-- 'Control.Lens.Traversal.forOf' l a ≡ 'iforOf' l a '.' 'const'+-- 'iforOf' ≡ 'flip' '.' 'itraverseOf'+-- @+--+-- @+-- 'iforOf' :: 'Functor' f     => 'IndexedLens' i s t a b       -> s -> (i -> a -> f b) -> f t+-- 'iforOf' :: 'Applicative' f => 'IndexedTraversal' i s t a b  -> s -> (i -> a -> f b) -> f t+-- 'iforOf' :: 'Apply' f       => 'IndexedTraversal1' i s t a b -> s -> (i -> a -> f b) -> f t+-- @+iforOf :: (Indexed i a (f b) -> s -> f t) -> s -> (i -> a -> f b) -> f t+iforOf = flip . itraverseOf+{-# INLINE iforOf #-}++-- | Map each element of a structure targeted by a 'Lens' to a monadic action,+-- evaluate these actions from left to right, and collect the results, with access+-- its position.+--+-- When you don't need access to the index 'mapMOf' is more liberal in what it can accept.+--+-- @+-- 'Control.Lens.Traversal.mapMOf' l ≡ 'imapMOf' l '.' 'const'+-- @+--+-- @+-- 'imapMOf' :: 'Monad' m => 'IndexedLens'       i s t a b -> (i -> a -> m b) -> s -> m t+-- 'imapMOf' :: 'Monad' m => 'IndexedTraversal'  i s t a b -> (i -> a -> m b) -> s -> m t+-- 'imapMOf' :: 'Bind'  m => 'IndexedTraversal1' i s t a b -> (i -> a -> m b) -> s -> m t+-- @+imapMOf :: Over (Indexed i) (WrappedMonad m) s t a b  -> (i -> a -> m b) -> s -> m t+imapMOf = coerce+{-# INLINE imapMOf #-}++-- | Map each element of a structure targeted by a 'Lens' to a monadic action,+-- evaluate these actions from left to right, and collect the results, with access+-- its position (and the arguments flipped).+--+-- @+-- 'Control.Lens.Traversal.forMOf' l a ≡ 'iforMOf' l a '.' 'const'+-- 'iforMOf' ≡ 'flip' '.' 'imapMOf'+-- @+--+-- @+-- 'iforMOf' :: 'Monad' m => 'IndexedLens' i s t a b      -> s -> (i -> a -> m b) -> m t+-- 'iforMOf' :: 'Monad' m => 'IndexedTraversal' i s t a b -> s -> (i -> a -> m b) -> m t+-- @+iforMOf :: (Indexed i a (WrappedMonad m b) -> s -> WrappedMonad m t) -> s -> (i -> a -> m b) -> m t+iforMOf = flip . imapMOf+{-# INLINE iforMOf #-}++-- | Generalizes 'Data.Traversable.mapAccumR' to an arbitrary 'IndexedTraversal' with access to the index.+--+-- 'imapAccumROf' accumulates state from right to left.+--+-- @+-- 'Control.Lens.Traversal.mapAccumROf' l ≡ 'imapAccumROf' l '.' 'const'+-- @+--+-- @+-- 'imapAccumROf' :: 'IndexedLens' i s t a b      -> (i -> acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+-- 'imapAccumROf' :: 'IndexedTraversal' i s t a b -> (i -> acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+-- @+imapAccumROf :: Over (Indexed i) (Backwards (State acc)) s t a b -> (i -> acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+imapAccumROf = imapAccumLOf . backwards+{-# INLINE imapAccumROf #-}++-- | Generalizes 'Data.Traversable.mapAccumL' to an arbitrary 'IndexedTraversal' with access to the index.+--+-- 'imapAccumLOf' accumulates state from left to right.+--+-- @+-- 'Control.Lens.Traversal.mapAccumLOf' l ≡ 'imapAccumLOf' l '.' 'const'+-- @+--+-- @+-- 'imapAccumLOf' :: 'IndexedLens' i s t a b      -> (i -> acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+-- 'imapAccumLOf' :: 'IndexedTraversal' i s t a b -> (i -> acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+-- @+imapAccumLOf :: Over (Indexed i) (State acc) s t a b -> (i -> acc -> a -> (acc, b)) -> acc -> s -> (acc, t)+imapAccumLOf l f acc0 s = swap (runState (l (Indexed g) s) acc0) where+  g i a = state $ \acc -> swap (f i acc a)+{-# INLINE imapAccumLOf #-}++------------------------------------------------------------------------------+-- Common Indexed Traversals+------------------------------------------------------------------------------++-- | Traverse any 'Traversable' container. This is an 'IndexedTraversal' that is indexed by ordinal position.+traversed :: Traversable f => IndexedTraversal Int (f a) (f b) a b+traversed = conjoined traverse (indexing traverse)+{-# INLINE [0] traversed #-}++imapList :: (Int -> a -> b) -> [a] -> [b]+imapList f = go 0+  where+    go i (x:xs) = f i x : go (i+1) xs+    go _ []     = []+{-# INLINE imapList #-}++{-# RULES+"traversed -> mapped"     traversed = sets fmap          :: Functor f => ASetter (f a) (f b) a b;+"traversed -> folded"     traversed = folded             :: Foldable f => Getting (Endo r) (f a) a;+"traversed -> ifolded"    traversed = folded             :: Foldable f => IndexedGetting Int (Endo r) (f a) a;+"traversed -> imapList"   traversed = isets imapList     :: AnIndexedSetter Int [a] [b] a b;+"traversed -> imapSeq"    traversed = isets mapWithIndex :: AnIndexedSetter Int (Seq a) (Seq b) a b;+"traversed -> imapVector" traversed = isets Vector.imap  :: AnIndexedSetter Int (Vector a) (Vector b) a b;+ #-}++-- | Traverse any 'Traversable1' container. This is an 'IndexedTraversal1' that is indexed by ordinal position.+traversed1 :: Traversable1 f => IndexedTraversal1 Int (f a) (f b) a b+traversed1 = conjoined traverse1 (indexing traverse1)+{-# INLINE traversed1 #-}++-- | Traverse any 'Traversable' container. This is an 'IndexedTraversal' that is indexed by ordinal position.+traversed64 :: Traversable f => IndexedTraversal Int64 (f a) (f b) a b+traversed64 = conjoined traverse (indexing64 traverse)+{-# INLINE traversed64 #-}++-- | This is the trivial empty 'Traversal'.+--+-- @+-- 'ignored' :: 'IndexedTraversal' i s s a b+-- @+--+-- @+-- 'ignored' ≡ 'const' 'pure'+-- @+--+-- >>> 6 & ignored %~ absurd+-- 6+ignored :: Applicative f => pafb -> s -> f s+ignored _ = pure+{-# INLINE ignored #-}++-- | Allows 'IndexedTraversal' the value at the smallest index.+class Ord k => TraverseMin k m | m -> k where+  -- | 'IndexedTraversal' of the element with the smallest index.+  traverseMin :: IndexedTraversal' k (m v) v++instance TraverseMin Int IntMap.IntMap where+  traverseMin f m = case IntMap.minViewWithKey m of+    Just ((k,a), _) -> indexed f k a <&> \v -> IntMap.updateMin (const (Just v)) m+    Nothing     -> pure m+  {-# INLINE traverseMin #-}++instance Ord k => TraverseMin k (Map k) where+  traverseMin f m = case Map.minViewWithKey m of+    Just ((k, a), _) -> indexed f k a <&> \v -> Map.updateMin (const (Just v)) m+    Nothing          -> pure m+  {-# INLINE traverseMin #-}++-- | Allows 'IndexedTraversal' of the value at the largest index.+class Ord k => TraverseMax k m | m -> k where+  -- | 'IndexedTraversal' of the element at the largest index.+  traverseMax :: IndexedTraversal' k (m v) v++instance TraverseMax Int IntMap.IntMap where+  traverseMax f m = case IntMap.maxViewWithKey m of+    Just ((k,a), _) -> indexed f k a <&> \v -> IntMap.updateMax (const (Just v)) m+    Nothing     -> pure m+  {-# INLINE traverseMax #-}++instance Ord k => TraverseMax k (Map k) where+  traverseMax f m = case Map.maxViewWithKey m of+    Just ((k, a), _) -> indexed f k a <&> \v -> Map.updateMax (const (Just v)) m+    Nothing          -> pure m+  {-# INLINE traverseMax #-}++-- | Traverse the /nth/ 'elementOf' a 'Traversal', 'Lens' or+-- 'Iso' if it exists.+--+-- >>> [[1],[3,4]] & elementOf (traverse.traverse) 1 .~ 5+-- [[1],[5,4]]+--+-- >>> [[1],[3,4]] ^? elementOf (folded.folded) 1+-- Just 3+--+-- >>> timingOut $ ['a'..] ^?! elementOf folded 5+-- 'f'+--+-- >>> timingOut $ take 10 $ elementOf traverse 3 .~ 16 $ [0..]+-- [0,1,2,16,4,5,6,7,8,9]+--+-- @+-- 'elementOf' :: 'Traversal'' s a -> 'Int' -> 'IndexedTraversal'' 'Int' s a+-- 'elementOf' :: 'Fold' s a       -> 'Int' -> 'IndexedFold' 'Int' s a+-- @+elementOf :: Applicative f+          => LensLike (Indexing f) s t a a+          -> Int+          -> IndexedLensLike Int f s t a a+elementOf l p = elementsOf l (p ==)+{-# INLINE elementOf #-}++-- | Traverse the /nth/ element of a 'Traversable' container.+--+-- @+-- 'element' ≡ 'elementOf' 'traverse'+-- @+element :: Traversable t => Int -> IndexedTraversal' Int (t a) a+element i = elementOf traverse i+{-# INLINE element #-}++-- | Traverse (or fold) selected elements of a 'Traversal' (or 'Fold') where their ordinal positions match a predicate.+--+-- @+-- 'elementsOf' :: 'Traversal'' s a -> ('Int' -> 'Bool') -> 'IndexedTraversal'' 'Int' s a+-- 'elementsOf' :: 'Fold' s a       -> ('Int' -> 'Bool') -> 'IndexedFold' 'Int' s a+-- @+elementsOf :: Applicative f+           => LensLike (Indexing f) s t a a+           -> (Int -> Bool)+           -> IndexedLensLike Int f s t a a+elementsOf l p iafb s = snd $ runIndexing (l (\a -> Indexing (\i -> i `seq` (i + 1, if p i then indexed iafb i a else pure a))) s) 0+{-# INLINE elementsOf #-}++-- | Traverse elements of a 'Traversable' container where their ordinal positions match a predicate.+--+-- @+-- 'elements' ≡ 'elementsOf' 'traverse'+-- @+elements :: Traversable t => (Int -> Bool) -> IndexedTraversal' Int (t a) a+elements i = elementsOf traverse i+{-# INLINE elements #-}++-- | Try to map a function over this 'Traversal', failing if the 'Traversal' has no targets.+--+-- >>> failover (element 3) (*2) [1,2] :: Maybe [Int]+-- Nothing+--+-- >>> failover _Left (*2) (Right 4) :: Maybe (Either Int Int)+-- Nothing+--+-- >>> failover _Right (*2) (Right 4) :: Maybe (Either Int Int)+-- Just (Right 8)+--+-- @+-- 'failover' :: Alternative m => Traversal s t a b -> (a -> b) -> s -> m t+-- @+failover :: Alternative m => LensLike ((,) Any) s t a b -> (a -> b) -> s -> m t+failover l afb s = case l ((,) (Any True) . afb) s of+  (Any True, t)  -> pure t+  (Any False, _) -> empty+{-# INLINE failover #-}++-- | Try to map a function which uses the index over this 'IndexedTraversal', failing if the 'IndexedTraversal' has no targets.+--+-- @+-- 'ifailover' :: Alternative m => IndexedTraversal i s t a b -> (i -> a -> b) -> s -> m t+-- @+ifailover :: Alternative m => Over (Indexed i) ((,) Any) s t a b -> (i -> a -> b) -> s -> m t+ifailover l iafb s = case l ((,) (Any True) `rmap` Indexed iafb) s of+  (Any True, t) -> pure t+  (Any False, _) -> empty+{-# INLINE ifailover #-}++-- | Try the first 'Traversal' (or 'Fold'), falling back on the second 'Traversal' (or 'Fold') if it returns no entries.+--+-- This is only a valid 'Traversal' if the second 'Traversal' is disjoint from the result of the first or returns+-- exactly the same results. These conditions are trivially met when given a 'Lens', 'Iso', 'Getter', 'Prism' or \"affine\" Traversal -- one that+-- has 0 or 1 target.+--+-- Mutatis mutandis for 'Fold'.+--+-- >>> [0,1,2,3] ^? failing (ix 1) (ix 2)+-- Just 1+--+-- >>> [0,1,2,3] ^? failing (ix 42) (ix 2)+-- Just 2+--+-- @+-- 'failing' :: 'Traversal' s t a b -> 'Traversal' s t a b -> 'Traversal' s t a b+-- 'failing' :: 'Prism' s t a b     -> 'Prism' s t a b     -> 'Traversal' s t a b+-- 'failing' :: 'Fold' s a          -> 'Fold' s a          -> 'Fold' s a+-- @+--+-- These cases are also supported, trivially, but are boring, because the left hand side always succeeds.+--+-- @+-- 'failing' :: 'Lens' s t a b      -> 'Traversal' s t a b -> 'Traversal' s t a b+-- 'failing' :: 'Iso' s t a b       -> 'Traversal' s t a b -> 'Traversal' s t a b+-- 'failing' :: 'Equality' s t a b  -> 'Traversal' s t a b -> 'Traversal' s t a b+-- 'failing' :: 'Getter' s a        -> 'Fold' s a          -> 'Fold' s a+-- @+--+-- If both of the inputs are indexed, the result is also indexed, so you can apply this to a pair of indexed+-- traversals or indexed folds, obtaining an indexed traversal or indexed fold.+--+-- @+-- 'failing' :: 'IndexedTraversal' i s t a b -> 'IndexedTraversal' i s t a b -> 'IndexedTraversal' i s t a b+-- 'failing' :: 'IndexedFold' i s a          -> 'IndexedFold' i s a          -> 'IndexedFold' i s a+-- @+--+-- These cases are also supported, trivially, but are boring, because the left hand side always succeeds.+--+-- @+-- 'failing' :: 'IndexedLens' i s t a b      -> 'IndexedTraversal' i s t a b -> 'IndexedTraversal' i s t a b+-- 'failing' :: 'IndexedGetter' i s a        -> 'IndexedGetter' i s a        -> 'IndexedFold' i s a+-- @+failing :: (Conjoined p, Applicative f) => Traversing p f s t a b -> Over p f s t a b -> Over p f s t a b+failing l r pafb s = case pins b of+  [] -> r pafb s+  _  -> bazaar pafb b+  where b = l sell s++infixl 5 `failing`++-- | Try the second traversal. If it returns no entries, try again with all entries from the first traversal, recursively.+--+-- @+-- 'deepOf' :: 'Fold' s s          -> 'Fold' s a                   -> 'Fold' s a+-- 'deepOf' :: 'Traversal'' s s    -> 'Traversal'' s a             -> 'Traversal'' s a+-- 'deepOf' :: 'Traversal' s t s t -> 'Traversal' s t a b          -> 'Traversal' s t a b+-- 'deepOf' :: 'Fold' s s          -> 'IndexedFold' i s a          -> 'IndexedFold' i s a+-- 'deepOf' :: 'Traversal' s t s t -> 'IndexedTraversal' i s t a b -> 'IndexedTraversal' i s t a b+-- @+deepOf :: (Conjoined p, Applicative f) => LensLike f s t s t -> Traversing p f s t a b -> Over p f s t a b+deepOf r l = failing l (r . deepOf r l)++-- | "Fuse" a 'Traversal' by reassociating all of the @('<*>')@ operations to the+-- left and fusing all of the 'fmap' calls into one. This is particularly+-- useful when constructing a 'Traversal' using operations from "GHC.Generics".+--+-- Given a pair of 'Traversal's 'foo' and 'bar',+--+-- @+-- 'confusing' (foo.bar) = foo.bar+-- @+--+-- However, @foo@ and @bar@ are each going to use the 'Applicative' they are given.+--+-- 'confusing' exploits the 'Yoneda' lemma to merge their separate uses of 'fmap' into a single 'fmap'.+-- and it further exploits an interesting property of the right Kan lift (or 'Curried') to left associate+-- all of the uses of @('<*>')@ to make it possible to fuse together more fmaps.+--+-- This is particularly effective when the choice of functor 'f' is unknown at compile+-- time or when the 'Traversal' @foo.bar@ in the above description is recursive or complex+-- enough to prevent inlining.+--+-- 'Control.Lens.Lens.fusing' is a version of this combinator suitable for fusing lenses.+--+-- @+-- 'confusing' :: 'Traversal' s t a b -> 'Traversal' s t a b+-- @+confusing :: Applicative f => LensLike (Curried (Yoneda f) (Yoneda f)) s t a b -> LensLike f s t a b+confusing t = \f -> lowerYoneda . lowerCurried . t (liftCurriedYoneda . f)+  where+  liftCurriedYoneda :: Applicative f => f a -> Curried (Yoneda f) (Yoneda f) a+  liftCurriedYoneda fa = Curried (`yap` fa)+  {-# INLINE liftCurriedYoneda #-}++  yap :: Applicative f => Yoneda f (a -> b) -> f a -> Yoneda f b+  yap (Yoneda k) fa = Yoneda (\ab_r -> k (ab_r .) <*> fa)+  {-# INLINE yap #-}++{-# INLINE confusing #-}++-- | Traverse a container using a specified 'Applicative'.+--+-- This is like 'traverseBy' where the 'Traversable' instance can be specified by any 'Traversal'+--+-- @+-- 'traverseByOf' 'traverse' ≡ 'traverseBy'+-- @+traverseByOf :: Traversal s t a b -> (forall x. x -> f x) -> (forall x y. f (x -> y) -> f x -> f y) -> (a -> f b) -> s -> f t+traverseByOf l pur app f = reifyApplicative pur app (l (ReflectedApplicative #. f))++-- | Sequence a container using a specified 'Applicative'.+--+-- This is like 'traverseBy' where the 'Traversable' instance can be specified by any 'Traversal'+--+-- @+-- 'sequenceByOf' 'traverse' ≡ 'sequenceBy'+-- @+sequenceByOf :: Traversal s t (f b) b -> (forall x. x -> f x) -> (forall x y. f (x -> y) -> f x -> f y) -> s -> f t+sequenceByOf l pur app = reifyApplicative pur app (l ReflectedApplicative)
src/Control/Lens/Tuple.hs view
@@ -1,284 +1,1335 @@ {-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FunctionalDependencies #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE UndecidableInstances #-}----------------------------------------------------------------------------------- |--- Module      :  Control.Lens.Tuple--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  Rank2Types------------------------------------------------------------------------------------module Control.Lens.Tuple-  (-  -- * Tuples-    Field1(..)-  , Field2(..)-  , Field3(..)-  , Field4(..)-  , Field5(..)-  , Field6(..)-  , Field7(..)-  , Field8(..)-  , Field9(..)-  ) where--import Control.Lens.Type-import Data.Functor---- $setup--- >>> import Control.Lens---- | Provides access to 1st field of a tuple.-class Field1 a b c d | a -> c, b -> d, a d -> b, b c -> a where-  -- | Access the 1st field of a tuple (and possibly change its type).-  ---  -- >>> (1,2)^._1-  -- 1-  ---  -- >>> _1 .~ "hello" $ (1,2)-  -- ("hello",2)-  ---  -- This can also be used on larger tuples as well-  ---  -- >>> _1 +~ 41 $ (1,2,3,4,5)-  -- (42,2,3,4,5)-  ---  -- @-  -- _1 :: 'Lens' (a,b) (a',b) a a'-  -- _1 :: 'Lens' (a,b,c) (a',b,c) a a'-  -- _1 :: 'Lens' (a,b,c,d) (a',b,c,d) a a'-  -- ...-  -- _1 :: 'Lens' (a,c,d,e,f,g,h,i) (a',b,c,d,e,f,g,h,i) a a'-  -- @-  _1 :: Lens a b c d--instance Field1 (a,b) (a',b) a a' where-  _1 k (a,b) = (\a' -> (a',b)) <$> k a-  {-# INLINE _1 #-}--instance Field1 (a,b,c) (a',b,c) a a' where-  _1 k (a,b,c) = (\a' -> (a',b,c)) <$> k a-  {-# INLINE _1 #-}--instance Field1 (a,b,c,d) (a',b,c,d) a a' where-  _1 k (a,b,c,d) = (\a' -> (a',b,c,d)) <$> k a-  {-# INLINE _1 #-}--instance Field1 (a,b,c,d,e) (a',b,c,d,e) a a' where-  _1 k (a,b,c,d,e) = (\a' -> (a',b,c,d,e)) <$> k a-  {-# INLINE _1 #-}--instance Field1 (a,b,c,d,e,f) (a',b,c,d,e,f) a a' where-  _1 k (a,b,c,d,e,f) = (\a' -> (a',b,c,d,e,f)) <$> k a-  {-# INLINE _1 #-}--instance Field1 (a,b,c,d,e,f,g) (a',b,c,d,e,f,g) a a' where-  _1 k (a,b,c,d,e,f,g) = (\a' -> (a',b,c,d,e,f,g)) <$> k a-  {-# INLINE _1 #-}--instance Field1 (a,b,c,d,e,f,g,h) (a',b,c,d,e,f,g,h) a a' where-  _1 k (a,b,c,d,e,f,g,h) = (\a' -> (a',b,c,d,e,f,g,h)) <$> k a-  {-# INLINE _1 #-}--instance Field1 (a,b,c,d,e,f,g,h,i) (a',b,c,d,e,f,g,h,i) a a' where-  _1 k (a,b,c,d,e,f,g,h,i) = (\a' -> (a',b,c,d,e,f,g,h,i)) <$> k a-  {-# INLINE _1 #-}---- | Provides access to the 2nd field of a tuple-class Field2 a b c d | a -> c, b -> d, a d -> b, b c -> a where-  -- | Access the 2nd field of a tuple-  ---  -- >>> _2 .~ "hello" $ (1,(),3,4)-  -- (1,"hello",3,4)-  ---  -- @-  -- 'Control.Lens.Fold.anyOf' '_2' :: (c -> 'Bool') -> (a, c) -> 'Bool'-  -- 'Data.Traversable.traverse' '.' '_2' :: ('Applicative' f, 'Data.Traversable.Traversable' t) => (a -> f b) -> t (c, a) -> f (t (c, b))-  -- 'Control.Lens.Fold.foldMapOf' ('Data.Traversable.traverse' '.' '_2') :: ('Data.Traversable.Traversable' t, 'Data.Monoid.Monoid' m) => (c -> m) -> t (b, c) -> m-  -- @-  _2 :: Lens a b c d--instance Field2 (a,b) (a,b') b b' where-  _2 k (a,b) = (\b' -> (a,b')) <$> k b-  {-# INLINE _2 #-}--instance Field2 (a,b,c) (a,b',c) b b' where-  _2 k (a,b,c) = (\b' -> (a,b',c)) <$> k b-  {-# INLINE _2 #-}--instance Field2 (a,b,c,d) (a,b',c,d) b b' where-  _2 k (a,b,c,d) = (\b' -> (a,b',c,d)) <$> k b-  {-# INLINE _2 #-}--instance Field2 (a,b,c,d,e) (a,b',c,d,e) b b' where-  _2 k (a,b,c,d,e) = (\b' -> (a,b',c,d,e)) <$> k b-  {-# INLINE _2 #-}--instance Field2 (a,b,c,d,e,f) (a,b',c,d,e,f) b b' where-  _2 k (a,b,c,d,e,f) = (\b' -> (a,b',c,d,e,f)) <$> k b-  {-# INLINE _2 #-}--instance Field2 (a,b,c,d,e,f,g) (a,b',c,d,e,f,g) b b' where-  _2 k (a,b,c,d,e,f,g) = (\b' -> (a,b',c,d,e,f,g)) <$> k b-  {-# INLINE _2 #-}--instance Field2 (a,b,c,d,e,f,g,h) (a,b',c,d,e,f,g,h) b b' where-  _2 k (a,b,c,d,e,f,g,h) = (\b' -> (a,b',c,d,e,f,g,h)) <$> k b-  {-# INLINE _2 #-}--instance Field2 (a,b,c,d,e,f,g,h,i) (a,b',c,d,e,f,g,h,i) b b' where-  _2 k (a,b,c,d,e,f,g,h,i) = (\b' -> (a,b',c,d,e,f,g,h,i)) <$> k b-  {-# INLINE _2 #-}---- | Provides access to the 3rd field of a tuple-class Field3 a b c d | a -> c, b -> d, a d -> b, b c -> a where-  -- | Access the 3rd field of a tuple-  _3 :: Lens a b c d--instance Field3 (a,b,c) (a,b,c') c c' where-  _3 k (a,b,c) = (\c' -> (a,b,c')) <$> k c-  {-# INLINE _3 #-}--instance Field3 (a,b,c,d) (a,b,c',d) c c' where-  _3 k (a,b,c,d) = (\c' -> (a,b,c',d)) <$> k c-  {-# INLINE _3 #-}--instance Field3 (a,b,c,d,e) (a,b,c',d,e) c c' where-  _3 k (a,b,c,d,e) = (\c' -> (a,b,c',d,e)) <$> k c-  {-# INLINE _3 #-}--instance Field3 (a,b,c,d,e,f) (a,b,c',d,e,f) c c' where-  _3 k (a,b,c,d,e,f) = (\c' -> (a,b,c',d,e,f)) <$> k c-  {-# INLINE _3 #-}--instance Field3 (a,b,c,d,e,f,g) (a,b,c',d,e,f,g) c c' where-  _3 k (a,b,c,d,e,f,g) = (\c' -> (a,b,c',d,e,f,g)) <$> k c-  {-# INLINE _3 #-}--instance Field3 (a,b,c,d,e,f,g,h) (a,b,c',d,e,f,g,h) c c' where-  _3 k (a,b,c,d,e,f,g,h) = (\c' -> (a,b,c',d,e,f,g,h)) <$> k c-  {-# INLINE _3 #-}--instance Field3 (a,b,c,d,e,f,g,h,i) (a,b,c',d,e,f,g,h,i) c c' where-  _3 k (a,b,c,d,e,f,g,h,i) = (\c' -> (a,b,c',d,e,f,g,h,i)) <$> k c-  {-# INLINE _3 #-}---- | Provide access to the 4th field of a tuple-class Field4 a b c d | a -> c, b -> d, a d -> b, b c -> a where-  -- | Access the 4th field of a tuple-  _4 :: Lens a b c d--instance Field4 (a,b,c,d) (a,b,c,d') d d' where-  _4 k (a,b,c,d) = (\d' -> (a,b,c,d')) <$> k d-  {-# INLINE _4 #-}--instance Field4 (a,b,c,d,e) (a,b,c,d',e) d d' where-  _4 k (a,b,c,d,e) = (\d' -> (a,b,c,d',e)) <$> k d-  {-# INLINE _4 #-}--instance Field4 (a,b,c,d,e,f) (a,b,c,d',e,f) d d' where-  _4 k (a,b,c,d,e,f) = (\d' -> (a,b,c,d',e,f)) <$> k d-  {-# INLINE _4 #-}--instance Field4 (a,b,c,d,e,f,g) (a,b,c,d',e,f,g) d d' where-  _4 k (a,b,c,d,e,f,g) = (\d' -> (a,b,c,d',e,f,g)) <$> k d-  {-# INLINE _4 #-}--instance Field4 (a,b,c,d,e,f,g,h) (a,b,c,d',e,f,g,h) d d' where-  _4 k (a,b,c,d,e,f,g,h) = (\d' -> (a,b,c,d',e,f,g,h)) <$> k d-  {-# INLINE _4 #-}--instance Field4 (a,b,c,d,e,f,g,h,i) (a,b,c,d',e,f,g,h,i) d d' where-  _4 k (a,b,c,d,e,f,g,h,i) = (\d' -> (a,b,c,d',e,f,g,h,i)) <$> k d-  {-# INLINE _4 #-}---- | Provides access to the 5th field of a tuple-class Field5 a b c d | a -> c, b -> d, a d -> b, b c -> a where-  -- | Access the 5th field of a tuple-  _5 :: Lens a b c d--instance Field5 (a,b,c,d,e) (a,b,c,d,e') e e' where-  _5 k (a,b,c,d,e) = (\e' -> (a,b,c,d,e')) <$> k e-  {-# INLINE _5 #-}--instance Field5 (a,b,c,d,e,f) (a,b,c,d,e',f) e e' where-  _5 k (a,b,c,d,e,f) = (\e' -> (a,b,c,d,e',f)) <$> k e-  {-# INLINE _5 #-}--instance Field5 (a,b,c,d,e,f,g) (a,b,c,d,e',f,g) e e' where-  _5 k (a,b,c,d,e,f,g) = (\e' -> (a,b,c,d,e',f,g)) <$> k e-  {-# INLINE _5 #-}--instance Field5 (a,b,c,d,e,f,g,h) (a,b,c,d,e',f,g,h) e e' where-  _5 k (a,b,c,d,e,f,g,h) = (\e' -> (a,b,c,d,e',f,g,h)) <$> k e-  {-# INLINE _5 #-}--instance Field5 (a,b,c,d,e,f,g,h,i) (a,b,c,d,e',f,g,h,i) e e' where-  _5 k (a,b,c,d,e,f,g,h,i) = (\e' -> (a,b,c,d,e',f,g,h,i)) <$> k e-  {-# INLINE _5 #-}---- | Provides access to the 6th element of a tuple-class Field6 a b c d | a -> c, b -> d, a d -> b, b c -> a where-  -- | Access the 6th field of a tuple-  _6 :: Lens a b c d--instance Field6 (a,b,c,d,e,f) (a,b,c,d,e,f') f f' where-  _6 k (a,b,c,d,e,f) = (\f' -> (a,b,c,d,e,f')) <$> k f-  {-# INLINE _6 #-}--instance Field6 (a,b,c,d,e,f,g) (a,b,c,d,e,f',g) f f' where-  _6 k (a,b,c,d,e,f,g) = (\f' -> (a,b,c,d,e,f',g)) <$> k f-  {-# INLINE _6 #-}--instance Field6 (a,b,c,d,e,f,g,h) (a,b,c,d,e,f',g,h) f f' where-  _6 k (a,b,c,d,e,f,g,h) = (\f' -> (a,b,c,d,e,f',g,h)) <$> k f-  {-# INLINE _6 #-}--instance Field6 (a,b,c,d,e,f,g,h,i) (a,b,c,d,e,f',g,h,i) f f' where-  _6 k (a,b,c,d,e,f,g,h,i) = (\f' -> (a,b,c,d,e,f',g,h,i)) <$> k f-  {-# INLINE _6 #-}---- | Provide access to the 7th field of a tuple-class Field7 a b c d | a -> c, b -> d, a d -> b, b c -> a where-  -- | Access the 7th field of a tuple-  _7 :: Lens a b c d--instance Field7 (a,b,c,d,e,f,g) (a,b,c,d,e,f,g') g g' where-  _7 k (a,b,c,d,e,f,g) = (\g' -> (a,b,c,d,e,f,g')) <$> k g-  {-# INLINE _7 #-}--instance Field7 (a,b,c,d,e,f,g,h) (a,b,c,d,e,f,g',h) g g' where-  _7 k (a,b,c,d,e,f,g,h) = (\g' -> (a,b,c,d,e,f,g',h)) <$> k g-  {-# INLINE _7 #-}--instance Field7 (a,b,c,d,e,f,g,h,i) (a,b,c,d,e,f,g',h,i) g g' where-  _7 k (a,b,c,d,e,f,g,h,i) = (\g' -> (a,b,c,d,e,f,g',h,i)) <$> k g-  {-# INLINE _7 #-}---- | Provide access to the 8th field of a tuple-class Field8 a b c d | a -> c, b -> d, a d -> b, b c -> a where-  -- | Access the 8th field of a tuple-  _8 :: Lens a b c d--instance Field8 (a,b,c,d,e,f,g,h) (a,b,c,d,e,f,g,h') h h' where-  _8 k (a,b,c,d,e,f,g,h) = (\h' -> (a,b,c,d,e,f,g,h')) <$> k h-  {-# INLINE _8 #-}--instance Field8 (a,b,c,d,e,f,g,h,i) (a,b,c,d,e,f,g,h',i) h h' where-  _8 k (a,b,c,d,e,f,g,h,i) = (\h' -> (a,b,c,d,e,f,g,h',i)) <$> k h-  {-# INLINE _8 #-}---- | Provides access to the 9th field of a tuple-class Field9 a b c d | a -> c, b -> d, a d -> b, b c -> a where-  -- | Access the 9th field of a tuple-  _9 :: Lens a b c d--instance Field9 (a,b,c,d,e,f,g,h,i) (a,b,c,d,e,f,g,h,i') i i' where-  _9 k (a,b,c,d,e,f,g,h,i) = (\i' -> (a,b,c,d,e,f,g,h,i')) <$> k i-  {-# INLINE _9 #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE EmptyDataDecls #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE DefaultSignatures #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE PolyKinds #-}++#include "lens-common.h"++-------------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Tuple+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  Rank2Types+--+-------------------------------------------------------------------------------+module Control.Lens.Tuple+  (+  -- * Tuples+    Field1(..)+  , Field2(..)+  , Field3(..)+  , Field4(..)+  , Field5(..)+  , Field6(..)+  , Field7(..)+  , Field8(..)+  , Field9(..)+  , Field10(..)+  , Field11(..)+  , Field12(..)+  , Field13(..)+  , Field14(..)+  , Field15(..)+  , Field16(..)+  , Field17(..)+  , Field18(..)+  , Field19(..)+  -- * Strict variations+  , _1', _2', _3', _4', _5', _6', _7', _8', _9'+  , _10', _11', _12', _13', _14', _15', _16'+  , _17', _18', _19'+  ) where++import           Prelude ()+import           Control.Lens.Lens+import           Control.Lens.Internal.Prelude+import           Data.Functor.Product  (Product (..))+import           Data.Kind+import           Data.Strict           (Pair (..))+import           GHC.Generics          ((:*:) (..), Generic (..), K1 (..),+                                        M1 (..), U1 (..))++-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens++-- | Provides access to 1st field of a tuple.+class Field1 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 1st field of a tuple (and possibly change its type).+  --+  -- >>> (1,2)^._1+  -- 1+  --+  -- >>> _1 .~ "hello" $ (1,2)+  -- ("hello",2)+  --+  -- >>> (1,2) & _1 .~ "hello"+  -- ("hello",2)+  --+  -- >>> _1 putStrLn ("hello","world")+  -- hello+  -- ((),"world")+  --+  -- This can also be used on larger tuples as well:+  --+  -- >>> (1,2,3,4,5) & _1 +~ 41+  -- (42,2,3,4,5)+  --+  -- @+  -- '_1' :: 'Lens' (a,b) (a',b) a a'+  -- '_1' :: 'Lens' (a,b,c) (a',b,c) a a'+  -- '_1' :: 'Lens' (a,b,c,d) (a',b,c,d) a a'+  -- ...+  -- '_1' :: 'Lens' (a,b,c,d,e,f,g,h,i) (a',b,c,d,e,f,g,h,i) a a'+  -- @+  _1 :: Lens s t a b+  default _1 :: (Generic s, Generic t, GIxed N0 (Rep s) (Rep t) a b)+             => Lens s t a b+  _1 = ix proxyN0+  {-# INLINE _1 #-}++instance Field1 (Identity a) (Identity b) a b where+  _1 f (Identity a) = Identity <$> f a++instance Field1 (Product f g a) (Product f' g a) (f a) (f' a) where+  _1 f (Pair a b) = flip Pair b <$> f a++instance Field1 ((f :*: g) p) ((f' :*: g) p) (f p) (f' p) where+  _1 f (l :*: r) = (:*: r) <$> f l++-- | @since 4.20+instance Field1 (Pair a b) (Pair a' b) a a' where+  _1 f (a :!: b) = (:!: b) <$> f a++-- | @+-- '_1' k ~(a,b) = (\\a' -> (a',b)) 'Data.Functor.<$>' k a+-- @+instance Field1 (a,b) (a',b) a a' where+  _1 k ~(a,b) = k a <&> \a' -> (a',b)+  {-# INLINE _1 #-}++instance Field1 (a,b,c) (a',b,c) a a' where+  _1 k ~(a,b,c) = k a <&> \a' -> (a',b,c)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d) (a',b,c,d) a a' where+  _1 k ~(a,b,c,d) = k a <&> \a' -> (a',b,c,d)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e) (a',b,c,d,e) a a' where+  _1 k ~(a,b,c,d,e) = k a <&> \a' -> (a',b,c,d,e)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e,f) (a',b,c,d,e,f) a a' where+  _1 k ~(a,b,c,d,e,f) = k a <&> \a' -> (a',b,c,d,e,f)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e,f,g) (a',b,c,d,e,f,g) a a' where+  _1 k ~(a,b,c,d,e,f,g) = k a <&> \a' -> (a',b,c,d,e,f,g)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e,f,g,h) (a',b,c,d,e,f,g,h) a a' where+  _1 k ~(a,b,c,d,e,f,g,h) = k a <&> \a' -> (a',b,c,d,e,f,g,h)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e,f,g,h,i) (a',b,c,d,e,f,g,h,i) a a' where+  _1 k ~(a,b,c,d,e,f,g,h,i) = k a <&> \a' -> (a',b,c,d,e,f,g,h,i)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e,f,g,h,i,j) (a',b,c,d,e,f,g,h,i,j) a a' where+  _1 k ~(a,b,c,d,e,f,g,h,i,j) = k a <&> \a' -> (a',b,c,d,e,f,g,h,i,j)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e,f,g,h,i,j,kk) (a',b,c,d,e,f,g,h,i,j,kk) a a' where+  _1 k ~(a,b,c,d,e,f,g,h,i,j,kk) = k a <&> \a' -> (a',b,c,d,e,f,g,h,i,j,kk)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e,f,g,h,i,j,kk,l) (a',b,c,d,e,f,g,h,i,j,kk,l) a a' where+  _1 k ~(a,b,c,d,e,f,g,h,i,j,kk,l) = k a <&> \a' -> (a',b,c,d,e,f,g,h,i,j,kk,l)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e,f,g,h,i,j,kk,l,m) (a',b,c,d,e,f,g,h,i,j,kk,l,m) a a' where+  _1 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m) = k a <&> \a' -> (a',b,c,d,e,f,g,h,i,j,kk,l,m)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n) (a',b,c,d,e,f,g,h,i,j,kk,l,m,n) a a' where+  _1 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n) = k a <&> \a' -> (a',b,c,d,e,f,g,h,i,j,kk,l,m,n)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a',b,c,d,e,f,g,h,i,j,kk,l,m,n,o) a a' where+  _1 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k a <&> \a' -> (a',b,c,d,e,f,g,h,i,j,kk,l,m,n,o)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a',b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) a a' where+  _1 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k a <&> \a' -> (a',b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a',b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) a a' where+  _1 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k a <&> \a' -> (a',b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a',b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) a a' where+  _1 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k a <&> \a' -> (a',b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r)+  {-# INLINE _1 #-}++instance Field1 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a',b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) a a' where+  _1 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k a <&> \a' -> (a',b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s)+  {-# INLINE _1 #-}++-- | Provides access to the 2nd field of a tuple.+class Field2 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 2nd field of a tuple.+  --+  -- >>> _2 .~ "hello" $ (1,(),3,4)+  -- (1,"hello",3,4)+  --+  -- >>> (1,2,3,4) & _2 *~ 3+  -- (1,6,3,4)+  --+  -- >>> _2 print (1,2)+  -- 2+  -- (1,())+  --+  -- @+  -- 'Control.Lens.Fold.anyOf' '_2' :: (s -> 'Bool') -> (a, s) -> 'Bool'+  -- 'Data.Traversable.traverse' '.' '_2' :: ('Control.Applicative.Applicative' f, 'Data.Traversable.Traversable' t) => (a -> f b) -> t (s, a) -> f (t (s, b))+  -- 'Control.Lens.Fold.foldMapOf' ('Data.Traversable.traverse' '.' '_2') :: ('Data.Traversable.Traversable' t, 'Data.Monoid.Monoid' m) => (s -> m) -> t (b, s) -> m+  -- @+  _2 :: Lens s t a b+  default _2 :: (Generic s, Generic t, GIxed N1 (Rep s) (Rep t) a b)+             => Lens s t a b+  _2 = ix proxyN1+  {-# INLINE _2 #-}++instance Field2 (Product f g a) (Product f g' a) (g a) (g' a) where+  _2 f (Pair a b) = Pair a <$> f b++instance Field2 ((f :*: g) p) ((f :*: g') p) (g p) (g' p) where+  _2 f (l :*: r) = (l :*:) <$> f r++-- | @since 4.20+instance Field2 (Pair a b) (Pair a b') b b' where+  _2 f (a :!: b) = (a :!:) <$> f b++-- | @+-- '_2' k ~(a,b) = (\\b' -> (a,b')) 'Data.Functor.<$>' k b+-- @+instance Field2 (a,b) (a,b') b b' where+  _2 k ~(a,b) = k b <&> \b' -> (a,b')+  {-# INLINE _2 #-}++instance Field2 (a,b,c) (a,b',c) b b' where+  _2 k ~(a,b,c) = k b <&> \b' -> (a,b',c)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d) (a,b',c,d) b b' where+  _2 k ~(a,b,c,d) = k b <&> \b' -> (a,b',c,d)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e) (a,b',c,d,e) b b' where+  _2 k ~(a,b,c,d,e) = k b <&> \b' -> (a,b',c,d,e)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e,f) (a,b',c,d,e,f) b b' where+  _2 k ~(a,b,c,d,e,f) = k b <&> \b' -> (a,b',c,d,e,f)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e,f,g) (a,b',c,d,e,f,g) b b' where+  _2 k ~(a,b,c,d,e,f,g) = k b <&> \b' -> (a,b',c,d,e,f,g)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e,f,g,h) (a,b',c,d,e,f,g,h) b b' where+  _2 k ~(a,b,c,d,e,f,g,h) = k b <&> \b' -> (a,b',c,d,e,f,g,h)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e,f,g,h,i) (a,b',c,d,e,f,g,h,i) b b' where+  _2 k ~(a,b,c,d,e,f,g,h,i) = k b <&> \b' -> (a,b',c,d,e,f,g,h,i)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e,f,g,h,i,j) (a,b',c,d,e,f,g,h,i,j) b b' where+  _2 k ~(a,b,c,d,e,f,g,h,i,j) = k b <&> \b' -> (a,b',c,d,e,f,g,h,i,j)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e,f,g,h,i,j,kk) (a,b',c,d,e,f,g,h,i,j,kk) b b' where+  _2 k ~(a,b,c,d,e,f,g,h,i,j,kk) = k b <&> \b' -> (a,b',c,d,e,f,g,h,i,j,kk)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e,f,g,h,i,j,kk,l) (a,b',c,d,e,f,g,h,i,j,kk,l) b b' where+  _2 k ~(a,b,c,d,e,f,g,h,i,j,kk,l) = k b <&> \b' -> (a,b',c,d,e,f,g,h,i,j,kk,l)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e,f,g,h,i,j,kk,l,m) (a,b',c,d,e,f,g,h,i,j,kk,l,m) b b' where+  _2 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m) = k b <&> \b' -> (a,b',c,d,e,f,g,h,i,j,kk,l,m)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n) (a,b',c,d,e,f,g,h,i,j,kk,l,m,n) b b' where+  _2 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n) = k b <&> \b' -> (a,b',c,d,e,f,g,h,i,j,kk,l,m,n)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a,b',c,d,e,f,g,h,i,j,kk,l,m,n,o) b b' where+  _2 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k b <&> \b' -> (a,b',c,d,e,f,g,h,i,j,kk,l,m,n,o)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b',c,d,e,f,g,h,i,j,kk,l,m,n,o,p) b b' where+  _2 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k b <&> \b' -> (a,b',c,d,e,f,g,h,i,j,kk,l,m,n,o,p)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b',c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) b b' where+  _2 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k b <&> \b' -> (a,b',c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b',c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) b b' where+  _2 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k b <&> \b' -> (a,b',c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r)+  {-# INLINE _2 #-}++instance Field2 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b',c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) b b' where+  _2 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k b <&> \b' -> (a,b',c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s)+  {-# INLINE _2 #-}+++-- | Provides access to the 3rd field of a tuple.+class Field3 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 3rd field of a tuple.+  _3 :: Lens s t a b+  default _3 :: (Generic s, Generic t, GIxed N2 (Rep s) (Rep t) a b)+             => Lens s t a b+  _3 = ix proxyN2+  {-# INLINE _3 #-}++instance Field3 (a,b,c) (a,b,c') c c' where+  _3 k ~(a,b,c) = k c <&> \c' -> (a,b,c')+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d) (a,b,c',d) c c' where+  _3 k ~(a,b,c,d) = k c <&> \c' -> (a,b,c',d)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e) (a,b,c',d,e) c c' where+  _3 k ~(a,b,c,d,e) = k c <&> \c' -> (a,b,c',d,e)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e,f) (a,b,c',d,e,f) c c' where+  _3 k ~(a,b,c,d,e,f) = k c <&> \c' -> (a,b,c',d,e,f)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e,f,g) (a,b,c',d,e,f,g) c c' where+  _3 k ~(a,b,c,d,e,f,g) = k c <&> \c' -> (a,b,c',d,e,f,g)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e,f,g,h) (a,b,c',d,e,f,g,h) c c' where+  _3 k ~(a,b,c,d,e,f,g,h) = k c <&> \c' -> (a,b,c',d,e,f,g,h)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e,f,g,h,i) (a,b,c',d,e,f,g,h,i) c c' where+  _3 k ~(a,b,c,d,e,f,g,h,i) = k c <&> \c' -> (a,b,c',d,e,f,g,h,i)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e,f,g,h,i,j) (a,b,c',d,e,f,g,h,i,j) c c' where+  _3 k ~(a,b,c,d,e,f,g,h,i,j) = k c <&> \c' -> (a,b,c',d,e,f,g,h,i,j)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e,f,g,h,i,j,kk) (a,b,c',d,e,f,g,h,i,j,kk) c c' where+  _3 k ~(a,b,c,d,e,f,g,h,i,j,kk) = k c <&> \c' -> (a,b,c',d,e,f,g,h,i,j,kk)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e,f,g,h,i,j,kk,l) (a,b,c',d,e,f,g,h,i,j,kk,l) c c' where+  _3 k ~(a,b,c,d,e,f,g,h,i,j,kk,l) = k c <&> \c' -> (a,b,c',d,e,f,g,h,i,j,kk,l)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e,f,g,h,i,j,kk,l,m) (a,b,c',d,e,f,g,h,i,j,kk,l,m) c c' where+  _3 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m) = k c <&> \c' -> (a,b,c',d,e,f,g,h,i,j,kk,l,m)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n) (a,b,c',d,e,f,g,h,i,j,kk,l,m,n) c c' where+  _3 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n) = k c <&> \c' -> (a,b,c',d,e,f,g,h,i,j,kk,l,m,n)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a,b,c',d,e,f,g,h,i,j,kk,l,m,n,o) c c' where+  _3 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k c <&> \c' -> (a,b,c',d,e,f,g,h,i,j,kk,l,m,n,o)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b,c',d,e,f,g,h,i,j,kk,l,m,n,o,p) c c' where+  _3 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k c <&> \c' -> (a,b,c',d,e,f,g,h,i,j,kk,l,m,n,o,p)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c',d,e,f,g,h,i,j,kk,l,m,n,o,p,q) c c' where+  _3 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k c <&> \c' -> (a,b,c',d,e,f,g,h,i,j,kk,l,m,n,o,p,q)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c',d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) c c' where+  _3 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k c <&> \c' -> (a,b,c',d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r)+  {-# INLINE _3 #-}++instance Field3 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c',d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) c c' where+  _3 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k c <&> \c' -> (a,b,c',d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s)+  {-# INLINE _3 #-}++-- | Provide access to the 4th field of a tuple.+class Field4 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 4th field of a tuple.+  _4 :: Lens s t a b+  default _4 :: (Generic s, Generic t, GIxed N3 (Rep s) (Rep t) a b)+             => Lens s t a b+  _4 = ix proxyN3+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d) (a,b,c,d') d d' where+  _4 k ~(a,b,c,d) = k d <&> \d' -> (a,b,c,d')+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e) (a,b,c,d',e) d d' where+  _4 k ~(a,b,c,d,e) = k d <&> \d' -> (a,b,c,d',e)+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e,f) (a,b,c,d',e,f) d d' where+  _4 k ~(a,b,c,d,e,f) = k d <&> \d' -> (a,b,c,d',e,f)+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e,f,g) (a,b,c,d',e,f,g) d d' where+  _4 k ~(a,b,c,d,e,f,g) = k d <&> \d' -> (a,b,c,d',e,f,g)+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e,f,g,h) (a,b,c,d',e,f,g,h) d d' where+  _4 k ~(a,b,c,d,e,f,g,h) = k d <&> \d' -> (a,b,c,d',e,f,g,h)+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e,f,g,h,i) (a,b,c,d',e,f,g,h,i) d d' where+  _4 k ~(a,b,c,d,e,f,g,h,i) = k d <&> \d' -> (a,b,c,d',e,f,g,h,i)+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e,f,g,h,i,j) (a,b,c,d',e,f,g,h,i,j) d d' where+  _4 k ~(a,b,c,d,e,f,g,h,i,j) = k d <&> \d' -> (a,b,c,d',e,f,g,h,i,j)+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e,f,g,h,i,j,kk) (a,b,c,d',e,f,g,h,i,j,kk) d d' where+  _4 k ~(a,b,c,d,e,f,g,h,i,j,kk) = k d <&> \d' -> (a,b,c,d',e,f,g,h,i,j,kk)+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e,f,g,h,i,j,kk,l) (a,b,c,d',e,f,g,h,i,j,kk,l) d d' where+  _4 k ~(a,b,c,d,e,f,g,h,i,j,kk,l) = k d <&> \d' -> (a,b,c,d',e,f,g,h,i,j,kk,l)+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e,f,g,h,i,j,kk,l,m) (a,b,c,d',e,f,g,h,i,j,kk,l,m) d d' where+  _4 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m) = k d <&> \d' -> (a,b,c,d',e,f,g,h,i,j,kk,l,m)+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n) (a,b,c,d',e,f,g,h,i,j,kk,l,m,n) d d' where+  _4 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n) = k d <&> \d' -> (a,b,c,d',e,f,g,h,i,j,kk,l,m,n)+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a,b,c,d',e,f,g,h,i,j,kk,l,m,n,o) d d' where+  _4 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k d <&> \d' -> (a,b,c,d',e,f,g,h,i,j,kk,l,m,n,o)+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b,c,d',e,f,g,h,i,j,kk,l,m,n,o,p) d d' where+  _4 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k d <&> \d' -> (a,b,c,d',e,f,g,h,i,j,kk,l,m,n,o,p)+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c,d',e,f,g,h,i,j,kk,l,m,n,o,p,q) d d' where+  _4 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k d <&> \d' -> (a,b,c,d',e,f,g,h,i,j,kk,l,m,n,o,p,q)+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d',e,f,g,h,i,j,kk,l,m,n,o,p,q,r) d d' where+  _4 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k d <&> \d' -> (a,b,c,d',e,f,g,h,i,j,kk,l,m,n,o,p,q,r)+  {-# INLINE _4 #-}++instance Field4 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d',e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) d d' where+  _4 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k d <&> \d' -> (a,b,c,d',e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s)+  {-# INLINE _4 #-}++-- | Provides access to the 5th field of a tuple.+class Field5 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 5th field of a tuple.+  _5 :: Lens s t a b+  default _5 :: (Generic s, Generic t, GIxed N4 (Rep s) (Rep t) a b)+             => Lens s t a b+  _5 = ix proxyN4+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e) (a,b,c,d,e') e e' where+  _5 k ~(a,b,c,d,e) = k e <&> \e' -> (a,b,c,d,e')+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e,f) (a,b,c,d,e',f) e e' where+  _5 k ~(a,b,c,d,e,f) = k e <&> \e' -> (a,b,c,d,e',f)+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e,f,g) (a,b,c,d,e',f,g) e e' where+  _5 k ~(a,b,c,d,e,f,g) = k e <&> \e' -> (a,b,c,d,e',f,g)+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e,f,g,h) (a,b,c,d,e',f,g,h) e e' where+  _5 k ~(a,b,c,d,e,f,g,h) = k e <&> \e' -> (a,b,c,d,e',f,g,h)+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e,f,g,h,i) (a,b,c,d,e',f,g,h,i) e e' where+  _5 k ~(a,b,c,d,e,f,g,h,i) = k e <&> \e' -> (a,b,c,d,e',f,g,h,i)+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e,f,g,h,i,j) (a,b,c,d,e',f,g,h,i,j) e e' where+  _5 k ~(a,b,c,d,e,f,g,h,i,j) = k e <&> \e' -> (a,b,c,d,e',f,g,h,i,j)+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e,f,g,h,i,j,kk) (a,b,c,d,e',f,g,h,i,j,kk) e e' where+  _5 k ~(a,b,c,d,e,f,g,h,i,j,kk) = k e <&> \e' -> (a,b,c,d,e',f,g,h,i,j,kk)+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e,f,g,h,i,j,kk,l) (a,b,c,d,e',f,g,h,i,j,kk,l) e e' where+  _5 k ~(a,b,c,d,e,f,g,h,i,j,kk,l) = k e <&> \e' -> (a,b,c,d,e',f,g,h,i,j,kk,l)+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e,f,g,h,i,j,kk,l,m) (a,b,c,d,e',f,g,h,i,j,kk,l,m) e e' where+  _5 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m) = k e <&> \e' -> (a,b,c,d,e',f,g,h,i,j,kk,l,m)+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n) (a,b,c,d,e',f,g,h,i,j,kk,l,m,n) e e' where+  _5 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n) = k e <&> \e' -> (a,b,c,d,e',f,g,h,i,j,kk,l,m,n)+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a,b,c,d,e',f,g,h,i,j,kk,l,m,n,o) e e' where+  _5 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k e <&> \e' -> (a,b,c,d,e',f,g,h,i,j,kk,l,m,n,o)+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b,c,d,e',f,g,h,i,j,kk,l,m,n,o,p) e e' where+  _5 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k e <&> \e' -> (a,b,c,d,e',f,g,h,i,j,kk,l,m,n,o,p)+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c,d,e',f,g,h,i,j,kk,l,m,n,o,p,q) e e' where+  _5 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k e <&> \e' -> (a,b,c,d,e',f,g,h,i,j,kk,l,m,n,o,p,q)+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d,e',f,g,h,i,j,kk,l,m,n,o,p,q,r) e e' where+  _5 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k e <&> \e' -> (a,b,c,d,e',f,g,h,i,j,kk,l,m,n,o,p,q,r)+  {-# INLINE _5 #-}++instance Field5 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e',f,g,h,i,j,kk,l,m,n,o,p,q,r,s) e e' where+  _5 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k e <&> \e' -> (a,b,c,d,e',f,g,h,i,j,kk,l,m,n,o,p,q,r,s)+  {-# INLINE _5 #-}++-- | Provides access to the 6th element of a tuple.+class Field6 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 6th field of a tuple.+  _6 :: Lens s t a b+  default _6 :: (Generic s, Generic t, GIxed N5 (Rep s) (Rep t) a b)+             => Lens s t a b+  _6 = ix proxyN5+  {-# INLINE _6 #-}++instance Field6 (a,b,c,d,e,f) (a,b,c,d,e,f') f f' where+  _6 k ~(a,b,c,d,e,f) = k f <&> \f' -> (a,b,c,d,e,f')+  {-# INLINE _6 #-}++instance Field6 (a,b,c,d,e,f,g) (a,b,c,d,e,f',g) f f' where+  _6 k ~(a,b,c,d,e,f,g) = k f <&> \f' -> (a,b,c,d,e,f',g)+  {-# INLINE _6 #-}++instance Field6 (a,b,c,d,e,f,g,h) (a,b,c,d,e,f',g,h) f f' where+  _6 k ~(a,b,c,d,e,f,g,h) = k f <&> \f' -> (a,b,c,d,e,f',g,h)+  {-# INLINE _6 #-}++instance Field6 (a,b,c,d,e,f,g,h,i) (a,b,c,d,e,f',g,h,i) f f' where+  _6 k ~(a,b,c,d,e,f,g,h,i) = k f <&> \f' -> (a,b,c,d,e,f',g,h,i)+  {-# INLINE _6 #-}++instance Field6 (a,b,c,d,e,f,g,h,i,j) (a,b,c,d,e,f',g,h,i,j) f f' where+  _6 k ~(a,b,c,d,e,f,g,h,i,j) = k f <&> \f' -> (a,b,c,d,e,f',g,h,i,j)+  {-# INLINE _6 #-}++instance Field6 (a,b,c,d,e,f,g,h,i,j,kk) (a,b,c,d,e,f',g,h,i,j,kk) f f' where+  _6 k ~(a,b,c,d,e,f,g,h,i,j,kk) = k f <&> \f' -> (a,b,c,d,e,f',g,h,i,j,kk)+  {-# INLINE _6 #-}++instance Field6 (a,b,c,d,e,f,g,h,i,j,kk,l) (a,b,c,d,e,f',g,h,i,j,kk,l) f f' where+  _6 k ~(a,b,c,d,e,f,g,h,i,j,kk,l) = k f <&> \f' -> (a,b,c,d,e,f',g,h,i,j,kk,l)+  {-# INLINE _6 #-}++instance Field6 (a,b,c,d,e,f,g,h,i,j,kk,l,m) (a,b,c,d,e,f',g,h,i,j,kk,l,m) f f' where+  _6 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m) = k f <&> \f' -> (a,b,c,d,e,f',g,h,i,j,kk,l,m)+  {-# INLINE _6 #-}++instance Field6 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n) (a,b,c,d,e,f',g,h,i,j,kk,l,m,n) f f' where+  _6 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n) = k f <&> \f' -> (a,b,c,d,e,f',g,h,i,j,kk,l,m,n)+  {-# INLINE _6 #-}++instance Field6 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a,b,c,d,e,f',g,h,i,j,kk,l,m,n,o) f f' where+  _6 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k f <&> \f' -> (a,b,c,d,e,f',g,h,i,j,kk,l,m,n,o)+  {-# INLINE _6 #-}++instance Field6 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b,c,d,e,f',g,h,i,j,kk,l,m,n,o,p) f f' where+  _6 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k f <&> \f' -> (a,b,c,d,e,f',g,h,i,j,kk,l,m,n,o,p)+  {-# INLINE _6 #-}++instance Field6 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c,d,e,f',g,h,i,j,kk,l,m,n,o,p,q) f f' where+  _6 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k f <&> \f' -> (a,b,c,d,e,f',g,h,i,j,kk,l,m,n,o,p,q)+  {-# INLINE _6 #-}++instance Field6 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d,e,f',g,h,i,j,kk,l,m,n,o,p,q,r) f f' where+  _6 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k f <&> \f' -> (a,b,c,d,e,f',g,h,i,j,kk,l,m,n,o,p,q,r)+  {-# INLINE _6 #-}++instance Field6 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e,f',g,h,i,j,kk,l,m,n,o,p,q,r,s) f f' where+  _6 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k f <&> \f' -> (a,b,c,d,e,f',g,h,i,j,kk,l,m,n,o,p,q,r,s)+  {-# INLINE _6 #-}++-- | Provide access to the 7th field of a tuple.+class Field7 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 7th field of a tuple.+  _7 :: Lens s t a b+  default _7 :: (Generic s, Generic t, GIxed N6 (Rep s) (Rep t) a b)+             => Lens s t a b+  _7 = ix proxyN6+  {-# INLINE _7 #-}++instance Field7 (a,b,c,d,e,f,g) (a,b,c,d,e,f,g') g g' where+  _7 k ~(a,b,c,d,e,f,g) = k g <&> \g' -> (a,b,c,d,e,f,g')+  {-# INLINE _7 #-}++instance Field7 (a,b,c,d,e,f,g,h) (a,b,c,d,e,f,g',h) g g' where+  _7 k ~(a,b,c,d,e,f,g,h) = k g <&> \g' -> (a,b,c,d,e,f,g',h)+  {-# INLINE _7 #-}++instance Field7 (a,b,c,d,e,f,g,h,i) (a,b,c,d,e,f,g',h,i) g g' where+  _7 k ~(a,b,c,d,e,f,g,h,i) = k g <&> \g' -> (a,b,c,d,e,f,g',h,i)+  {-# INLINE _7 #-}++instance Field7 (a,b,c,d,e,f,g,h,i,j) (a,b,c,d,e,f,g',h,i,j) g g' where+  _7 k ~(a,b,c,d,e,f,g,h,i,j) = k g <&> \g' -> (a,b,c,d,e,f,g',h,i,j)+  {-# INLINE _7 #-}++instance Field7 (a,b,c,d,e,f,g,h,i,j,kk) (a,b,c,d,e,f,g',h,i,j,kk) g g' where+  _7 k ~(a,b,c,d,e,f,g,h,i,j,kk) = k g <&> \g' -> (a,b,c,d,e,f,g',h,i,j,kk)+  {-# INLINE _7 #-}++instance Field7 (a,b,c,d,e,f,g,h,i,j,kk,l) (a,b,c,d,e,f,g',h,i,j,kk,l) g g' where+  _7 k ~(a,b,c,d,e,f,g,h,i,j,kk,l) = k g <&> \g' -> (a,b,c,d,e,f,g',h,i,j,kk,l)+  {-# INLINE _7 #-}++instance Field7 (a,b,c,d,e,f,g,h,i,j,kk,l,m) (a,b,c,d,e,f,g',h,i,j,kk,l,m) g g' where+  _7 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m) = k g <&> \g' -> (a,b,c,d,e,f,g',h,i,j,kk,l,m)+  {-# INLINE _7 #-}++instance Field7 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n) (a,b,c,d,e,f,g',h,i,j,kk,l,m,n) g g' where+  _7 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n) = k g <&> \g' -> (a,b,c,d,e,f,g',h,i,j,kk,l,m,n)+  {-# INLINE _7 #-}++instance Field7 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a,b,c,d,e,f,g',h,i,j,kk,l,m,n,o) g g' where+  _7 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k g <&> \g' -> (a,b,c,d,e,f,g',h,i,j,kk,l,m,n,o)+  {-# INLINE _7 #-}++instance Field7 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b,c,d,e,f,g',h,i,j,kk,l,m,n,o,p) g g' where+  _7 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k g <&> \g' -> (a,b,c,d,e,f,g',h,i,j,kk,l,m,n,o,p)+  {-# INLINE _7 #-}++instance Field7 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c,d,e,f,g',h,i,j,kk,l,m,n,o,p,q) g g' where+  _7 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k g <&> \g' -> (a,b,c,d,e,f,g',h,i,j,kk,l,m,n,o,p,q)+  {-# INLINE _7 #-}++instance Field7 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d,e,f,g',h,i,j,kk,l,m,n,o,p,q,r) g g' where+  _7 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k g <&> \g' -> (a,b,c,d,e,f,g',h,i,j,kk,l,m,n,o,p,q,r)+  {-# INLINE _7 #-}++instance Field7 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e,f,g',h,i,j,kk,l,m,n,o,p,q,r,s) g g' where+  _7 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k g <&> \g' -> (a,b,c,d,e,f,g',h,i,j,kk,l,m,n,o,p,q,r,s)+  {-# INLINE _7 #-}++-- | Provide access to the 8th field of a tuple.+class Field8 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 8th field of a tuple.+  _8 :: Lens s t a b+  default _8 :: (Generic s, Generic t, GIxed N7 (Rep s) (Rep t) a b)+             => Lens s t a b+  _8 = ix proxyN7+  {-# INLINE _8 #-}++instance Field8 (a,b,c,d,e,f,g,h) (a,b,c,d,e,f,g,h') h h' where+  _8 k ~(a,b,c,d,e,f,g,h) = k h <&> \h' -> (a,b,c,d,e,f,g,h')+  {-# INLINE _8 #-}++instance Field8 (a,b,c,d,e,f,g,h,i) (a,b,c,d,e,f,g,h',i) h h' where+  _8 k ~(a,b,c,d,e,f,g,h,i) = k h <&> \h' -> (a,b,c,d,e,f,g,h',i)+  {-# INLINE _8 #-}++instance Field8 (a,b,c,d,e,f,g,h,i,j) (a,b,c,d,e,f,g,h',i,j) h h' where+  _8 k ~(a,b,c,d,e,f,g,h,i,j) = k h <&> \h' -> (a,b,c,d,e,f,g,h',i,j)+  {-# INLINE _8 #-}++instance Field8 (a,b,c,d,e,f,g,h,i,j,kk) (a,b,c,d,e,f,g,h',i,j,kk) h h' where+  _8 k ~(a,b,c,d,e,f,g,h,i,j,kk) = k h <&> \h' -> (a,b,c,d,e,f,g,h',i,j,kk)+  {-# INLINE _8 #-}++instance Field8 (a,b,c,d,e,f,g,h,i,j,kk,l) (a,b,c,d,e,f,g,h',i,j,kk,l) h h' where+  _8 k ~(a,b,c,d,e,f,g,h,i,j,kk,l) = k h <&> \h' -> (a,b,c,d,e,f,g,h',i,j,kk,l)+  {-# INLINE _8 #-}++instance Field8 (a,b,c,d,e,f,g,h,i,j,kk,l,m) (a,b,c,d,e,f,g,h',i,j,kk,l,m) h h' where+  _8 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m) = k h <&> \h' -> (a,b,c,d,e,f,g,h',i,j,kk,l,m)+  {-# INLINE _8 #-}++instance Field8 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n) (a,b,c,d,e,f,g,h',i,j,kk,l,m,n) h h' where+  _8 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n) = k h <&> \h' -> (a,b,c,d,e,f,g,h',i,j,kk,l,m,n)+  {-# INLINE _8 #-}++instance Field8 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a,b,c,d,e,f,g,h',i,j,kk,l,m,n,o) h h' where+  _8 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k h <&> \h' -> (a,b,c,d,e,f,g,h',i,j,kk,l,m,n,o)+  {-# INLINE _8 #-}++instance Field8 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b,c,d,e,f,g,h',i,j,kk,l,m,n,o,p) h h' where+  _8 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k h <&> \h' -> (a,b,c,d,e,f,g,h',i,j,kk,l,m,n,o,p)+  {-# INLINE _8 #-}++instance Field8 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c,d,e,f,g,h',i,j,kk,l,m,n,o,p,q) h h' where+  _8 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k h <&> \h' -> (a,b,c,d,e,f,g,h',i,j,kk,l,m,n,o,p,q)+  {-# INLINE _8 #-}++instance Field8 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d,e,f,g,h',i,j,kk,l,m,n,o,p,q,r) h h' where+  _8 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k h <&> \h' -> (a,b,c,d,e,f,g,h',i,j,kk,l,m,n,o,p,q,r)+  {-# INLINE _8 #-}++instance Field8 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e,f,g,h',i,j,kk,l,m,n,o,p,q,r,s) h h' where+  _8 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k h <&> \h' -> (a,b,c,d,e,f,g,h',i,j,kk,l,m,n,o,p,q,r,s)+  {-# INLINE _8 #-}++-- | Provides access to the 9th field of a tuple.+class Field9 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 9th field of a tuple.+  _9 :: Lens s t a b+  default _9 :: (Generic s, Generic t, GIxed N8 (Rep s) (Rep t) a b)+             => Lens s t a b+  _9 = ix proxyN8+  {-# INLINE _9 #-}++instance Field9 (a,b,c,d,e,f,g,h,i) (a,b,c,d,e,f,g,h,i') i i' where+  _9 k ~(a,b,c,d,e,f,g,h,i) = k i <&> \i' -> (a,b,c,d,e,f,g,h,i')+  {-# INLINE _9 #-}++instance Field9 (a,b,c,d,e,f,g,h,i,j) (a,b,c,d,e,f,g,h,i',j) i i' where+  _9 k ~(a,b,c,d,e,f,g,h,i,j) = k i <&> \i' -> (a,b,c,d,e,f,g,h,i',j)+  {-# INLINE _9 #-}++instance Field9 (a,b,c,d,e,f,g,h,i,j,kk) (a,b,c,d,e,f,g,h,i',j,kk) i i' where+  _9 k ~(a,b,c,d,e,f,g,h,i,j,kk) = k i <&> \i' -> (a,b,c,d,e,f,g,h,i',j,kk)+  {-# INLINE _9 #-}++instance Field9 (a,b,c,d,e,f,g,h,i,j,kk,l) (a,b,c,d,e,f,g,h,i',j,kk,l) i i' where+  _9 k ~(a,b,c,d,e,f,g,h,i,j,kk,l) = k i <&> \i' -> (a,b,c,d,e,f,g,h,i',j,kk,l)+  {-# INLINE _9 #-}++instance Field9 (a,b,c,d,e,f,g,h,i,j,kk,l,m) (a,b,c,d,e,f,g,h,i',j,kk,l,m) i i' where+  _9 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m) = k i <&> \i' -> (a,b,c,d,e,f,g,h,i',j,kk,l,m)+  {-# INLINE _9 #-}++instance Field9 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n) (a,b,c,d,e,f,g,h,i',j,kk,l,m,n) i i' where+  _9 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n) = k i <&> \i' -> (a,b,c,d,e,f,g,h,i',j,kk,l,m,n)+  {-# INLINE _9 #-}++instance Field9 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a,b,c,d,e,f,g,h,i',j,kk,l,m,n,o) i i' where+  _9 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k i <&> \i' -> (a,b,c,d,e,f,g,h,i',j,kk,l,m,n,o)+  {-# INLINE _9 #-}++instance Field9 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b,c,d,e,f,g,h,i',j,kk,l,m,n,o,p) i i' where+  _9 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k i <&> \i' -> (a,b,c,d,e,f,g,h,i',j,kk,l,m,n,o,p)+  {-# INLINE _9 #-}++instance Field9 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c,d,e,f,g,h,i',j,kk,l,m,n,o,p,q) i i' where+  _9 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k i <&> \i' -> (a,b,c,d,e,f,g,h,i',j,kk,l,m,n,o,p,q)+  {-# INLINE _9 #-}++instance Field9 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d,e,f,g,h,i',j,kk,l,m,n,o,p,q,r) i i' where+  _9 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k i <&> \i' -> (a,b,c,d,e,f,g,h,i',j,kk,l,m,n,o,p,q,r)+  {-# INLINE _9 #-}++instance Field9 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e,f,g,h,i',j,kk,l,m,n,o,p,q,r,s) i i' where+  _9 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k i <&> \i' -> (a,b,c,d,e,f,g,h,i',j,kk,l,m,n,o,p,q,r,s)+  {-# INLINE _9 #-}++-- | Provides access to the 10th field of a tuple.+class Field10 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 10th field of a tuple.+  _10 :: Lens s t a b+  default _10 :: (Generic s, Generic t, GIxed N9 (Rep s) (Rep t) a b)+             => Lens s t a b+  _10 = ix proxyN9+  {-# INLINE _10 #-}++instance Field10 (a,b,c,d,e,f,g,h,i,j) (a,b,c,d,e,f,g,h,i,j') j j' where+  _10 k ~(a,b,c,d,e,f,g,h,i,j) = k j <&> \j' -> (a,b,c,d,e,f,g,h,i,j')+  {-# INLINE _10 #-}++instance Field10 (a,b,c,d,e,f,g,h,i,j,kk) (a,b,c,d,e,f,g,h,i,j',kk) j j' where+  _10 k ~(a,b,c,d,e,f,g,h,i,j,kk) = k j <&> \j' -> (a,b,c,d,e,f,g,h,i,j',kk)+  {-# INLINE _10 #-}++instance Field10 (a,b,c,d,e,f,g,h,i,j,kk,l) (a,b,c,d,e,f,g,h,i,j',kk,l) j j' where+  _10 k ~(a,b,c,d,e,f,g,h,i,j,kk,l) = k j <&> \j' -> (a,b,c,d,e,f,g,h,i,j',kk,l)+  {-# INLINE _10 #-}++instance Field10 (a,b,c,d,e,f,g,h,i,j,kk,l,m) (a,b,c,d,e,f,g,h,i,j',kk,l,m) j j' where+  _10 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m) = k j <&> \j' -> (a,b,c,d,e,f,g,h,i,j',kk,l,m)+  {-# INLINE _10 #-}++instance Field10 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n) (a,b,c,d,e,f,g,h,i,j',kk,l,m,n) j j' where+  _10 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n) = k j <&> \j' -> (a,b,c,d,e,f,g,h,i,j',kk,l,m,n)+  {-# INLINE _10 #-}++instance Field10 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a,b,c,d,e,f,g,h,i,j',kk,l,m,n,o) j j' where+  _10 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k j <&> \j' -> (a,b,c,d,e,f,g,h,i,j',kk,l,m,n,o)+  {-# INLINE _10 #-}++instance Field10 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b,c,d,e,f,g,h,i,j',kk,l,m,n,o,p) j j' where+  _10 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k j <&> \j' -> (a,b,c,d,e,f,g,h,i,j',kk,l,m,n,o,p)+  {-# INLINE _10 #-}++instance Field10 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c,d,e,f,g,h,i,j',kk,l,m,n,o,p,q) j j' where+  _10 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k j <&> \j' -> (a,b,c,d,e,f,g,h,i,j',kk,l,m,n,o,p,q)+  {-# INLINE _10 #-}++instance Field10 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d,e,f,g,h,i,j',kk,l,m,n,o,p,q,r) j j' where+  _10 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k j <&> \j' -> (a,b,c,d,e,f,g,h,i,j',kk,l,m,n,o,p,q,r)+  {-# INLINE _10 #-}++instance Field10 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e,f,g,h,i,j',kk,l,m,n,o,p,q,r,s) j j' where+  _10 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k j <&> \j' -> (a,b,c,d,e,f,g,h,i,j',kk,l,m,n,o,p,q,r,s)+  {-# INLINE _10 #-}++-- | Provides access to the 11th field of a tuple.+class Field11 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 11th field of a tuple.+  _11 :: Lens s t a b+  default _11 :: (Generic s, Generic t, GIxed N10 (Rep s) (Rep t) a b)+             => Lens s t a b+  _11 = ix proxyN10+  {-# INLINE _11 #-}++instance Field11 (a,b,c,d,e,f,g,h,i,j,kk) (a,b,c,d,e,f,g,h,i,j,kk') kk kk' where+  _11 k ~(a,b,c,d,e,f,g,h,i,j,kk) = k kk <&> \kk' -> (a,b,c,d,e,f,g,h,i,j,kk')+  {-# INLINE _11 #-}++instance Field11 (a,b,c,d,e,f,g,h,i,j,kk,l) (a,b,c,d,e,f,g,h,i,j,kk',l) kk kk' where+  _11 k ~(a,b,c,d,e,f,g,h,i,j,kk,l) = k kk <&> \kk' -> (a,b,c,d,e,f,g,h,i,j,kk',l)+  {-# INLINE _11 #-}++instance Field11 (a,b,c,d,e,f,g,h,i,j,kk,l,m) (a,b,c,d,e,f,g,h,i,j,kk',l,m) kk kk' where+  _11 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m) = k kk <&> \kk' -> (a,b,c,d,e,f,g,h,i,j,kk',l,m)+  {-# INLINE _11 #-}++instance Field11 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n) (a,b,c,d,e,f,g,h,i,j,kk',l,m,n) kk kk' where+  _11 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n) = k kk <&> \kk' -> (a,b,c,d,e,f,g,h,i,j,kk',l,m,n)+  {-# INLINE _11 #-}++instance Field11 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a,b,c,d,e,f,g,h,i,j,kk',l,m,n,o) kk kk' where+  _11 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k kk <&> \kk' -> (a,b,c,d,e,f,g,h,i,j,kk',l,m,n,o)+  {-# INLINE _11 #-}++instance Field11 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b,c,d,e,f,g,h,i,j,kk',l,m,n,o,p) kk kk' where+  _11 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k kk <&> \kk' -> (a,b,c,d,e,f,g,h,i,j,kk',l,m,n,o,p)+  {-# INLINE _11 #-}++instance Field11 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c,d,e,f,g,h,i,j,kk',l,m,n,o,p,q) kk kk' where+  _11 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k kk <&> \kk' -> (a,b,c,d,e,f,g,h,i,j,kk',l,m,n,o,p,q)+  {-# INLINE _11 #-}++instance Field11 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d,e,f,g,h,i,j,kk',l,m,n,o,p,q,r) kk kk' where+  _11 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k kk <&> \kk' -> (a,b,c,d,e,f,g,h,i,j,kk',l,m,n,o,p,q,r)+  {-# INLINE _11 #-}++instance Field11 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e,f,g,h,i,j,kk',l,m,n,o,p,q,r,s) kk kk' where+  _11 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k kk <&> \kk' -> (a,b,c,d,e,f,g,h,i,j,kk',l,m,n,o,p,q,r,s)+  {-# INLINE _11 #-}++-- | Provides access to the 12th field of a tuple.+class Field12 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 12th field of a tuple.+  _12 :: Lens s t a b+  default _12 :: (Generic s, Generic t, GIxed N11 (Rep s) (Rep t) a b)+             => Lens s t a b+  _12 = ix proxyN11+  {-# INLINE _12 #-}++instance Field12 (a,b,c,d,e,f,g,h,i,j,kk,l) (a,b,c,d,e,f,g,h,i,j,kk,l') l l' where+  _12 k ~(a,b,c,d,e,f,g,h,i,j,kk,l) = k l <&> \l' -> (a,b,c,d,e,f,g,h,i,j,kk,l')+  {-# INLINE _12 #-}++instance Field12 (a,b,c,d,e,f,g,h,i,j,kk,l,m) (a,b,c,d,e,f,g,h,i,j,kk,l',m) l l' where+  _12 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m) = k l <&> \l' -> (a,b,c,d,e,f,g,h,i,j,kk,l',m)+  {-# INLINE _12 #-}++instance Field12 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n) (a,b,c,d,e,f,g,h,i,j,kk,l',m,n) l l' where+  _12 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n) = k l <&> \l' -> (a,b,c,d,e,f,g,h,i,j,kk,l',m,n)+  {-# INLINE _12 #-}++instance Field12 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a,b,c,d,e,f,g,h,i,j,kk,l',m,n,o) l l' where+  _12 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k l <&> \l' -> (a,b,c,d,e,f,g,h,i,j,kk,l',m,n,o)+  {-# INLINE _12 #-}++instance Field12 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b,c,d,e,f,g,h,i,j,kk,l',m,n,o,p) l l' where+  _12 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k l <&> \l' -> (a,b,c,d,e,f,g,h,i,j,kk,l',m,n,o,p)+  {-# INLINE _12 #-}++instance Field12 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c,d,e,f,g,h,i,j,kk,l',m,n,o,p,q) l l' where+  _12 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k l <&> \l' -> (a,b,c,d,e,f,g,h,i,j,kk,l',m,n,o,p,q)+  {-# INLINE _12 #-}++instance Field12 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d,e,f,g,h,i,j,kk,l',m,n,o,p,q,r) l l' where+  _12 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k l <&> \l' -> (a,b,c,d,e,f,g,h,i,j,kk,l',m,n,o,p,q,r)+  {-# INLINE _12 #-}++instance Field12 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e,f,g,h,i,j,kk,l',m,n,o,p,q,r,s) l l' where+  _12 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k l <&> \l' -> (a,b,c,d,e,f,g,h,i,j,kk,l',m,n,o,p,q,r,s)+  {-# INLINE _12 #-}++-- | Provides access to the 13th field of a tuple.+class Field13 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 13th field of a tuple.+  _13 :: Lens s t a b+  default _13 :: (Generic s, Generic t, GIxed N12 (Rep s) (Rep t) a b)+             => Lens s t a b+  _13 = ix proxyN12+  {-# INLINE _13 #-}++instance Field13 (a,b,c,d,e,f,g,h,i,j,kk,l,m) (a,b,c,d,e,f,g,h,i,j,kk,l,m') m m' where+  _13 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m) = k m <&> \m' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m')+  {-# INLINE _13 #-}++instance Field13 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n) (a,b,c,d,e,f,g,h,i,j,kk,l,m',n) m m' where+  _13 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n) = k m <&> \m' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m',n)+  {-# INLINE _13 #-}++instance Field13 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a,b,c,d,e,f,g,h,i,j,kk,l,m',n,o) m m' where+  _13 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k m <&> \m' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m',n,o)+  {-# INLINE _13 #-}++instance Field13 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b,c,d,e,f,g,h,i,j,kk,l,m',n,o,p) m m' where+  _13 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k m <&> \m' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m',n,o,p)+  {-# INLINE _13 #-}++instance Field13 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c,d,e,f,g,h,i,j,kk,l,m',n,o,p,q) m m' where+  _13 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k m <&> \m' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m',n,o,p,q)+  {-# INLINE _13 #-}++instance Field13 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d,e,f,g,h,i,j,kk,l,m',n,o,p,q,r) m m' where+  _13 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k m <&> \m' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m',n,o,p,q,r)+  {-# INLINE _13 #-}++instance Field13 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e,f,g,h,i,j,kk,l,m',n,o,p,q,r,s) m m' where+  _13 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k m <&> \m' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m',n,o,p,q,r,s)+  {-# INLINE _13 #-}++-- | Provides access to the 14th field of a tuple.+class Field14 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 14th field of a tuple.+  _14 :: Lens s t a b+  default _14 :: (Generic s, Generic t, GIxed N13 (Rep s) (Rep t) a b)+             => Lens s t a b+  _14 = ix proxyN13+  {-# INLINE _14 #-}++instance Field14 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n') n n' where+  _14 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n) = k n <&> \n' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n')+  {-# INLINE _14 #-}++instance Field14 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n',o) n n' where+  _14 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k n <&> \n' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n',o)+  {-# INLINE _14 #-}++instance Field14 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n',o,p) n n' where+  _14 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k n <&> \n' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n',o,p)+  {-# INLINE _14 #-}++instance Field14 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n',o,p,q) n n' where+  _14 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k n <&> \n' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n',o,p,q)+  {-# INLINE _14 #-}++instance Field14 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n',o,p,q,r) n n' where+  _14 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k n <&> \n' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n',o,p,q,r)+  {-# INLINE _14 #-}++instance Field14 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n',o,p,q,r,s) n n' where+  _14 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k n <&> \n' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n',o,p,q,r,s)+  {-# INLINE _14 #-}++-- | Provides access to the 15th field of a tuple.+class Field15 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 15th field of a tuple.+  _15 :: Lens s t a b+  default _15 :: (Generic s, Generic t, GIxed N14 (Rep s) (Rep t) a b)+             => Lens s t a b+  _15 = ix proxyN14+  {-# INLINE _15 #-}++instance Field15 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o') o o' where+  _15 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o) = k o <&> \o' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o')+  {-# INLINE _15 #-}++instance Field15 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o',p) o o' where+  _15 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k o <&> \o' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o',p)+  {-# INLINE _15 #-}++instance Field15 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o',p,q) o o' where+  _15 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k o <&> \o' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o',p,q)+  {-# INLINE _15 #-}++instance Field15 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o',p,q,r) o o' where+  _15 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k o <&> \o' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o',p,q,r)+  {-# INLINE _15 #-}++instance Field15 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o',p,q,r,s) o o' where+  _15 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k o <&> \o' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o',p,q,r,s)+  {-# INLINE _15 #-}++-- | Provides access to the 16th field of a tuple.+class Field16 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 16th field of a tuple.+  _16 :: Lens s t a b+  default _16 :: (Generic s, Generic t, GIxed N15 (Rep s) (Rep t) a b)+             => Lens s t a b+  _16 = ix proxyN15+  {-# INLINE _16 #-}++instance Field16 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p') p p' where+  _16 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p) = k p <&> \p' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p')+  {-# INLINE _16 #-}++instance Field16 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p',q) p p' where+  _16 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k p <&> \p' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p',q)+  {-# INLINE _16 #-}++instance Field16 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p',q,r) p p' where+  _16 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k p <&> \p' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p',q,r)+  {-# INLINE _16 #-}++instance Field16 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p',q,r,s) p p' where+  _16 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k p <&> \p' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p',q,r,s)+  {-# INLINE _16 #-}++-- | Provides access to the 17th field of a tuple.+class Field17 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 17th field of a tuple.+  _17 :: Lens s t a b+  default _17 :: (Generic s, Generic t, GIxed N16 (Rep s) (Rep t) a b)+             => Lens s t a b+  _17 = ix proxyN16+  {-# INLINE _17 #-}++instance Field17 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q') q q' where+  _17 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q) = k q <&> \q' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q')+  {-# INLINE _17 #-}++instance Field17 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q',r) q q' where+  _17 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k q <&> \q' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q',r)+  {-# INLINE _17 #-}++instance Field17 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q',r,s) q q' where+  _17 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k q <&> \q' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q',r,s)+  {-# INLINE _17 #-}++-- | Provides access to the 18th field of a tuple.+class Field18 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 18th field of a tuple.+  _18 :: Lens s t a b+  default _18 :: (Generic s, Generic t, GIxed N17 (Rep s) (Rep t) a b)+             => Lens s t a b+  _18 = ix proxyN17+  {-# INLINE _18 #-}++instance Field18 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r') r r' where+  _18 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r) = k r <&> \r' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r')+  {-# INLINE _18 #-}++instance Field18 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r',s) r r' where+  _18 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k r <&> \r' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r',s)+  {-# INLINE _18 #-}++-- | Provides access to the 19th field of a tuple.+class Field19 s t a b | s -> a, t -> b, s b -> t, t a -> s where+  -- | Access the 19th field of a tuple.+  _19 :: Lens s t a b+  default _19 :: (Generic s, Generic t, GIxed N18 (Rep s) (Rep t) a b)+             => Lens s t a b+  _19 = ix proxyN18+  {-# INLINE _19 #-}++instance Field19 (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s') s s' where+  _19 k ~(a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s) = k s <&> \s' -> (a,b,c,d,e,f,g,h,i,j,kk,l,m,n,o,p,q,r,s')+  {-# INLINE _19 #-}++-- Strict versions of the _1 .. _19 operations++-- | Strict version of '_1'+_1' :: Field1 s t a b => Lens s t a b+_1' = \f !x -> _1 f x+{-# INLINE _1' #-}++-- | Strict version of '_2'+_2' :: Field2 s t a b => Lens s t a b+_2' = \f !x -> _2 f x+{-# INLINE _2' #-}++-- | Strict version of '_3'+_3' :: Field3 s t a b => Lens s t a b+_3' = \f !x -> _3 f x+{-# INLINE _3' #-}++-- | Strict version of '_4'+_4' :: Field4 s t a b => Lens s t a b+_4' = \f !x -> _4 f x+{-# INLINE _4' #-}++-- | Strict version of '_5'+_5' :: Field5 s t a b => Lens s t a b+_5' = \f !x -> _5 f x+{-# INLINE _5' #-}++-- | Strict version of '_6'+_6' :: Field6 s t a b => Lens s t a b+_6' = \f !x -> _6 f x+{-# INLINE _6' #-}++-- | Strict version of '_7'+_7' :: Field7 s t a b => Lens s t a b+_7' = \f !x -> _7 f x+{-# INLINE _7' #-}++-- | Strict version of '_8'+_8' :: Field8 s t a b => Lens s t a b+_8' = \f !x -> _8 f x+{-# INLINE _8' #-}++-- | Strict version of '_9'+_9' :: Field9 s t a b => Lens s t a b+_9' = \f !x -> _9 f x+{-# INLINE _9' #-}++-- | Strict version of '_10'+_10' :: Field10 s t a b => Lens s t a b+_10' = \f !x -> _10 f x+{-# INLINE _10' #-}++-- | Strict version of '_11'+_11' :: Field11 s t a b => Lens s t a b+_11' = \f !x -> _11 f x+{-# INLINE _11' #-}++-- | Strict version of '_12'+_12' :: Field12 s t a b => Lens s t a b+_12' = \f !x -> _12 f x+{-# INLINE _12' #-}++-- | Strict version of '_13'+_13' :: Field13 s t a b => Lens s t a b+_13' = \f !x -> _13 f x+{-# INLINE _13' #-}++-- | Strict version of '_14'+_14' :: Field14 s t a b => Lens s t a b+_14' = \f !x -> _14 f x+{-# INLINE _14' #-}++-- | Strict version of '_15'+_15' :: Field15 s t a b => Lens s t a b+_15' = \f !x -> _15 f x+{-# INLINE _15' #-}++-- | Strict version of '_16'+_16' :: Field16 s t a b => Lens s t a b+_16' = \f !x -> _16 f x+{-# INLINE _16' #-}++-- | Strict version of '_17'+_17' :: Field17 s t a b => Lens s t a b+_17' = \f !x -> _17 f x+{-# INLINE _17' #-}++-- | Strict version of '_18'+_18' :: Field18 s t a b => Lens s t a b+_18' = \f !x -> _18 f x+{-# INLINE _18' #-}++-- | Strict version of '_19'+_19' :: Field19 s t a b => Lens s t a b+_19' = \f !x -> _19 f x+{-# INLINE _19' #-}+++ix :: (Generic s, Generic t, GIxed n (Rep s) (Rep t) a b) => f n -> Lens s t a b+ix n f = fmap to . gix n f . from+{-# INLINE ix #-}++type family GSize (f :: Type -> Type)+type instance GSize U1 = Z+type instance GSize (K1 i c) = S Z+type instance GSize (M1 i c f) = GSize f+type instance GSize (a :*: b) = Add (GSize a) (GSize b)++class GIxed n s t a b | n s -> a, n t -> b, n s b -> t, n t a -> s where+  gix :: f n -> Lens (s x) (t x) a b++instance GIxed N0 (K1 i a) (K1 i b) a b where+  gix _ = dimap unK1 (fmap K1)+  {-# INLINE gix #-}++instance GIxed n s t a b => GIxed n (M1 i c s) (M1 i c t) a b where+  gix n = dimap unM1 (fmap M1) . gix n+  {-# INLINE gix #-}++instance (p ~ GT (GSize s) n,+          p ~ GT (GSize t) n,+          GIxed' p n s s' t t' a b)+      => GIxed n (s :*: s') (t :*: t') a b where+  gix = gix' (Proxy :: Proxy p)+  {-# INLINE gix #-}++-- $gixed-fundeps+-- >>> :set -XDeriveGeneric -XFlexibleInstances -XMultiParamTypeClasses+-- >>> import GHC.Generics (Generic)+-- >>> data Product a b = a :* b deriving Generic+-- >>> instance Field1 (Product a b) (Product a' b) a a'+-- >>> instance Field2 (Product a b) (Product a b') b b'++class (p ~ GT (GSize s) n,+       p ~ GT (GSize t) n)+   => GIxed' p n s s' t t' a b | p n s s' -> a+                               , p n t t' -> b+                               , p n s s' b -> t t'+                               , p n t t' a -> s s' where+  gix' :: f p -> g n -> Lens ((s :*: s') x) ((t :*: t') x) a b++instance (GT (GSize s) n ~ T,+          GT (GSize t) n ~ T,+          GIxed n s t a b)+      => GIxed' T n s s' t s' a b where+  gix' _ n f (s :*: s') = (:*: s') <$> gix n f s+  {-# INLINE gix' #-}++instance (GT (GSize s) n ~ F,+          n' ~ Subtract (GSize s) n,+          GIxed n' s' t' a b)+      => GIxed' F n s s' s t' a b where+  gix' _ _  f (s :*: s') = (s :*:) <$> gix (Proxy :: Proxy n') f s'+  {-# INLINE gix' #-}++data Z+data S a++data T+data F++type family Add x y+type instance Add Z y = y+type instance Add (S x) y = S (Add x y)++type family Subtract x y+type instance Subtract Z x = x+type instance Subtract (S x) (S y) = Subtract x y++type family GT x y+type instance GT Z x = F+type instance GT (S x) Z = T+type instance GT (S x) (S y) = GT x y++type N0 = Z+type N1 = S N0+type N2 = S N1+type N3 = S N2+type N4 = S N3+type N5 = S N4+type N6 = S N5+type N7 = S N6+type N8 = S N7+type N9 = S N8+type N10 = S N9+type N11 = S N10+type N12 = S N11+type N13 = S N12+type N14 = S N13+type N15 = S N14+type N16 = S N15+type N17 = S N16+type N18 = S N17++proxyN0 :: Proxy N0+proxyN0 = Proxy+{-# INLINE proxyN0 #-}++proxyN1 :: Proxy N1+proxyN1 = Proxy+{-# INLINE proxyN1 #-}++proxyN2 :: Proxy N2+proxyN2 = Proxy+{-# INLINE proxyN2 #-}++proxyN3 :: Proxy N3+proxyN3 = Proxy+{-# INLINE proxyN3 #-}++proxyN4 :: Proxy N4+proxyN4 = Proxy+{-# INLINE proxyN4 #-}++proxyN5 :: Proxy N5+proxyN5 = Proxy+{-# INLINE proxyN5 #-}++proxyN6 :: Proxy N6+proxyN6 = Proxy+{-# INLINE proxyN6 #-}++proxyN7 :: Proxy N7+proxyN7 = Proxy+{-# INLINE proxyN7 #-}++proxyN8 :: Proxy N8+proxyN8 = Proxy+{-# INLINE proxyN8 #-}++proxyN9 :: Proxy N9+proxyN9 = Proxy+{-# INLINE proxyN9 #-}++proxyN10 :: Proxy N10+proxyN10 = Proxy+{-# INLINE proxyN10 #-}++proxyN11 :: Proxy N11+proxyN11 = Proxy+{-# INLINE proxyN11 #-}++proxyN12 :: Proxy N12+proxyN12 = Proxy+{-# INLINE proxyN12 #-}++proxyN13 :: Proxy N13+proxyN13 = Proxy+{-# INLINE proxyN13 #-}++proxyN14 :: Proxy N14+proxyN14 = Proxy+{-# INLINE proxyN14 #-}++proxyN15 :: Proxy N15+proxyN15 = Proxy+{-# INLINE proxyN15 #-}++proxyN16 :: Proxy N16+proxyN16 = Proxy+{-# INLINE proxyN16 #-}++proxyN17 :: Proxy N17+proxyN17 = Proxy+{-# INLINE proxyN17 #-}++proxyN18 :: Proxy N18+proxyN18 = Proxy+{-# INLINE proxyN18 #-}
src/Control/Lens/Type.hs view
@@ -1,109 +1,88 @@ {-# LANGUAGE CPP #-}+{-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-}-{-# LANGUAGE LiberalTypeSynonyms #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE Trustworthy #-} -#ifndef MIN_VERSION_mtl-#define MIN_VERSION_mtl(x,y,z) 1+#if __GLASGOW_HASKELL__ >= 806+{-# LANGUAGE PolyKinds #-}+#else+{-# LANGUAGE TypeInType #-} #endif- ------------------------------------------------------------------------------- -- | -- Module      :  Control.Lens.Type--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional -- Portability :  Rank2Types ----- A @'Lens' a b c d@ is a purely functional reference.------ While a 'Control.Lens.Traversal.Traversal' could be used for--- 'Control.Lens.Getter.Getting' like a valid 'Control.Lens.Fold.Fold',--- it wasn't a valid 'Control.Lens.Getter.Getter' as 'Applicative' wasn't a superclass of--- 'Control.Lens.Getter.Gettable'.------ 'Functor', however is the superclass of both.------ @type 'Lens' a b c d = forall f. 'Functor' f => (c -> f d) -> a -> f b@------ Every 'Lens' is a valid 'Control.Lens.Setter.Setter', choosing @f@ =--- 'Control.Lens.Getter.Mutator'.------ Every 'Lens' can be used for 'Control.Lens.Getter.Getting' like a--- 'Control.Lens.Fold.Fold' that doesn't use the 'Applicative' or--- 'Control.Lens.Getter.Gettable'.------ Every 'Lens' is a valid 'Control.Lens.Traversal.Traversal' that only uses--- the 'Functor' part of the 'Applicative' it is supplied.------ Every 'Lens' can be used for 'Control.Lens.Getter.Getting' like a valid--- 'Control.Lens.Getter.Getter', since 'Functor' is a superclass of 'Control.Lens.Getter.Gettable'------ Since every 'Lens' can be used for 'Control.Lens.Getter.Getting' like a--- valid 'Control.Lens.Getter.Getter' it follows that it must view exactly one element in the--- structure.------ The lens laws follow from this property and the desire for it to act like--- a 'Data.Traversable.Traversable' when used as a--- 'Control.Lens.Traversal.Traversal'.+-- This module exports the majority of the types that need to appear in user+-- signatures or in documentation when talking about lenses. The remaining types+-- for consuming lenses are distributed across various modules in the hierarchy. ------------------------------------------------------------------------------- module Control.Lens.Type   (-  -- * Lenses-    Lens+  -- * Other+    Equality, Equality', As+  , Iso, Iso'+  , Prism , Prism'+  , Review , AReview+  -- * Lenses, Folds and Traversals+  , Lens, Lens'+  , Traversal, Traversal'+  , Traversal1, Traversal1'+  , Setter, Setter'+  , Getter, Fold+  , Fold1+  -- * Indexed+  , IndexedLens, IndexedLens'+  , IndexedTraversal, IndexedTraversal'+  , IndexedTraversal1, IndexedTraversal1'+  , IndexedSetter, IndexedSetter'+  , IndexedGetter, IndexedFold+  , IndexedFold1+  -- * Index-Preserving+  , IndexPreservingLens, IndexPreservingLens'+  , IndexPreservingTraversal, IndexPreservingTraversal'+  , IndexPreservingTraversal1, IndexPreservingTraversal1'+  , IndexPreservingSetter, IndexPreservingSetter'+  , IndexPreservingGetter, IndexPreservingFold+  , IndexPreservingFold1+  -- * Common   , Simple-  , lens-  , (%%~)-  , (%%=)--  , resultAt--  -- * Lateral Composition-  , choosing-  , chosen-  , alongside--  -- * Setting Functionally with Passthrough-  , (<%~), (<+~), (<-~), (<*~), (<//~)-  , (<^~), (<^^~), (<**~)-  , (<||~), (<&&~)-  , (<<%~), (<<.~)--  -- * Setting State with Passthrough-  , (<%=), (<+=), (<-=), (<*=), (<//=)-  , (<^=), (<^^=), (<**=)-  , (<||=), (<&&=)-  , (<<%=), (<<.=)--  -- * Cloning Lenses-  , cloneLens-  , ReifiedLens(..)--  -- * Simplified and In-Progress-  , LensLike-  , Overloaded-  , SimpleLens-  , SimpleLensLike-  , SimpleOverloaded-  , SimpleReifiedLens+  , LensLike, LensLike'+  , Over, Over'+  , IndexedLensLike, IndexedLensLike'+  , Optical, Optical'+  , Optic, Optic'   ) where -import Control.Applicative              as Applicative-import Control.Lens.Internal-import Control.Monad.State.Class        as State+import Prelude () +import Control.Lens.Internal.Prelude+import Control.Lens.Internal.Setter+import Control.Lens.Internal.Indexed+import Data.Bifunctor+import Data.Functor.Apply+import Data.Kind+ -- $setup+-- >>> :set -XNoOverloadedStrings -- >>> import Control.Lens--infixr 4 %%~-infix  4 %%=-infixr 4 <+~, <*~, <-~, <//~, <^~, <^^~, <**~, <&&~, <||~, <%~, <<%~, <<.~-infix  4 <+=, <*=, <-=, <//=, <^=, <^^=, <**=, <&&=, <||=, <%=, <<%=, <<.=-+-- >>> import Debug.SimpleReflect.Expr+-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g,h)+-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f+-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g+-- >>> let h :: Expr -> Expr -> Expr; h = Debug.SimpleReflect.Vars.h+-- >>> let getter :: Expr -> Expr; getter = fun "getter"+-- >>> let setter :: Expr -> Expr -> Expr; setter = fun "setter"+-- >>> import Numeric.Natural+-- >>> let nat :: Prism' Integer Natural; nat = prism toInteger $ \i -> if i < 0 then Left i else Right (fromInteger i)  ------------------------------------------------------------------------------- -- Lenses@@ -112,572 +91,535 @@ -- | A 'Lens' is actually a lens family as described in -- <http://comonad.com/reader/2012/mirrored-lenses/>. ----- With great power comes great responsibility and a 'Lens'is subject to the--- three common sense lens laws:+-- With great power comes great responsibility and a 'Lens' is subject to the+-- three common sense 'Lens' laws: -- -- 1) You get back what you put in: ----- @'Control.Lens.Getter.view' l ('Control.Lens.Setter.set' l b a)  ≡ b@+-- @+-- 'Control.Lens.Getter.view' l ('Control.Lens.Setter.set' l v s)  ≡ v+-- @ -- -- 2) Putting back what you got doesn't change anything: ----- @'Control.Lens.Setter.set' l ('Control.Lens.Getter.view' l a) a  ≡ a@+-- @+-- 'Control.Lens.Setter.set' l ('Control.Lens.Getter.view' l s) s  ≡ s+-- @ -- -- 3) Setting twice is the same as setting once: ----- @'Control.Lens.Setter.set' l c ('Control.Lens.Setter.set' l b a) ≡ 'Control.Lens.Setter.set' l c a@+-- @+-- 'Control.Lens.Setter.set' l v' ('Control.Lens.Setter.set' l v s) ≡ 'Control.Lens.Setter.set' l v' s+-- @ -- -- These laws are strong enough that the 4 type parameters of a 'Lens' cannot -- vary fully independently. For more on how they interact, read the \"Why is -- it a Lens Family?\" section of -- <http://comonad.com/reader/2012/mirrored-lenses/>. ----- Every 'Lens' can be used directly as a 'Control.Lens.Setter.Setter' or--- 'Control.Lens.Traversal.Traversal'.+-- There are some emergent properties of these laws: --+-- 1) @'Control.Lens.Setter.set' l s@ must be injective for every @s@ This is a consequence of law #1+--+-- 2) @'Control.Lens.Setter.set' l@ must be surjective, because of law #2, which indicates that it is possible to obtain any 'v' from some 's' such that @'Control.Lens.Setter.set' s v = s@+--+-- 3) Given just the first two laws you can prove a weaker form of law #3 where the values @v@ that you are setting match:+--+-- @+-- 'Control.Lens.Setter.set' l v ('Control.Lens.Setter.set' l v s) ≡ 'Control.Lens.Setter.set' l v s+-- @+--+-- Every 'Lens' can be used directly as a 'Control.Lens.Setter.Setter' or 'Traversal'.+-- -- You can also use a 'Lens' for 'Control.Lens.Getter.Getting' as if it were a--- 'Control.Lens.Fold.Fold' or 'Control.Lens.Getter.Getter'.+-- 'Fold' or 'Getter'. ----- Since every lens is a valid 'Control.Lens.Traversal.Traversal', the--- traversal laws are required of any lenses you create:+-- Since every 'Lens' is a valid 'Traversal', the+-- 'Traversal' laws are required of any 'Lens' you create: -- -- @ -- l 'pure' ≡ 'pure' -- 'fmap' (l f) '.' l g ≡ 'Data.Functor.Compose.getCompose' '.' l ('Data.Functor.Compose.Compose' '.' 'fmap' f '.' g) -- @ ----- @type 'Lens' a b c d = forall f. 'Functor' f => 'LensLike' f a b c d@-type Lens a b c d = forall f. Functor f => (c -> f d) -> a -> f b---- | A 'Simple' 'Lens', 'Simple' 'Control.Lens.Traversal.Traversal', ... can--- be used instead of a 'Lens','Control.Lens.Traversal.Traversal', ...--- whenever the type variables don't change upon setting a value.--- -- @--- 'Data.Complex.Lens.imaginary' :: 'Simple' 'Lens' ('Data.Complex.Complex' a) a--- 'Data.List.Lens.traverseHead' :: 'Simple' 'Control.Lens.Lens.Traversal' [a] a+-- type 'Lens' s t a b = forall f. 'Functor' f => 'LensLike' f s t a b -- @------ Note: To use this alias in your own code with @'LensLike' f@ or--- 'Control.Lens.Setter.Setter', you may have to turn on @LiberalTypeSynonyms@.-type Simple f a b = f a a b b+type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t --- | @type 'SimpleLens' = 'Simple' 'Lens'@-type SimpleLens a b = Lens a a b b+-- | @+-- type 'Lens'' = 'Simple' 'Lens'+-- @+type Lens' s a = Lens s s a a --- | @type 'SimpleLensLike' f = 'Simple' ('LensLike' f)@-type SimpleLensLike f a b = LensLike f a a b b+-- | Every 'IndexedLens' is a valid 'Lens' and a valid 'Control.Lens.Traversal.IndexedTraversal'.+type IndexedLens i s t a b = forall f p. (Indexable i p, Functor f) => p a (f b) -> s -> f t ------------------------------ Constructing Lenses---------------------------+-- | @+-- type 'IndexedLens'' i = 'Simple' ('IndexedLens' i)+-- @+type IndexedLens' i s a = IndexedLens i s s a a --- | Build a 'Lens' from a getter and a setter.------ @'lens' :: 'Functor' f => (a -> c) -> (a -> d -> b) -> (c -> f d) -> a -> f b@-lens :: (a -> c) -> (a -> d -> b) -> Lens a b c d-lens ac adb cfd a = adb a <$> cfd (ac a)-{-# INLINE lens #-}+-- | An 'IndexPreservingLens' leaves any index it is composed with alone.+type IndexPreservingLens s t a b = forall p f. (Conjoined p, Functor f) => p a (f b) -> p s (f t) ----------------------------------------------------------------------------------- LensLike--------------------------------------------------------------------------------+-- | @+-- type 'IndexPreservingLens'' = 'Simple' 'IndexPreservingLens'+-- @+type IndexPreservingLens' s a = IndexPreservingLens s s a a --- |--- Many combinators that accept a 'Lens' can also accept a--- 'Control.Lens.Traversal.Traversal' in limited situations.------ They do so by specializing the type of 'Functor' that they require of the--- caller.------ If a function accepts a @'LensLike' f a b c d@ for some 'Functor' @f@,--- then they may be passed a 'Lens'.------ Further, if @f@ is an 'Applicative', they may also be passed a--- 'Control.Lens.Traversal.Traversal'.-type LensLike f a b c d = (c -> f d) -> a -> f b+------------------------------------------------------------------------------+-- Traversals+------------------------------------------------------------------------------ --- | ('%%~') can be used in one of two scenarios:------ When applied to a 'Lens', it can edit the target of the 'Lens' in a--- structure, extracting a functorial result.------ When applied to a 'Control.Lens.Traversal.Traversal', it can edit the--- targets of the 'Traversals', extracting an applicative summary of its--- actions.------ For all that the definition of this combinator is just:+-- | A 'Traversal' can be used directly as a 'Control.Lens.Setter.Setter' or a 'Fold' (but not as a 'Lens') and provides+-- the ability to both read and update multiple fields, subject to some relatively weak 'Traversal' laws. ----- @('%%~') ≡ 'id'@+-- These have also been known as multilenses, but they have the signature and spirit of -- -- @--- ('%%~') :: 'Functor' f =>     'Control.Lens.Iso.Iso' a b c d       -> (c -> f d) -> a -> f b--- ('%%~') :: 'Functor' f =>     'Lens' a b c d      -> (c -> f d) -> a -> f b--- ('%%~') :: 'Applicative' f => 'Control.Lens.Traversal.Traversal' a b c d -> (c -> f d) -> a -> f b+-- 'Data.Traversable.traverse' :: 'Data.Traversable.Traversable' f => 'Traversal' (f a) (f b) a b -- @ ----- It may be beneficial to think about it as if it had these even more--- restrictive types, however:------ When applied to a 'Control.Lens.Traversal.Traversal', it can edit the--- targets of the 'Traversals', extracting a supplemental monoidal summary--- of its actions, by choosing @f = ((,) m)@------ @--- ('%%~') ::             'Control.Lens.Iso.Iso' a b c d       -> (c -> (e, d)) -> a -> (e, b)--- ('%%~') ::             'Lens' a b c d      -> (c -> (e, d)) -> a -> (e, b)--- ('%%~') :: 'Monoid' m => 'Control.Lens.Traversal.Traversal' a b c d -> (c -> (m, d)) -> a -> (m, b)--- @-(%%~) :: LensLike f a b c d -> (c -> f d) -> a -> f b-(%%~) = id-{-# INLINE (%%~) #-}---- | Modify the target of a 'Lens' in the current state returning some extra--- information of @c@ or modify all targets of a--- 'Control.Lens.Traversal.Traversal' in the current state, extracting extra--- information of type @c@ and return a monoidal summary of the changes.+-- and the more evocative name suggests their application. ----- @('%%=') ≡ ('state' '.')@+-- Most of the time the 'Traversal' you will want to use is just 'Data.Traversable.traverse', but you can also pass any+-- 'Lens' or 'Iso' as a 'Traversal', and composition of a 'Traversal' (or 'Lens' or 'Iso') with a 'Traversal' (or 'Lens' or 'Iso')+-- using ('.') forms a valid 'Traversal'. ----- It may be useful to think of ('%%='), instead, as having either of the--- following more restricted type signatures:+-- The laws for a 'Traversal' @t@ follow from the laws for 'Data.Traversable.Traversable' as stated in \"The Essence of the Iterator Pattern\". -- -- @--- ('%%=') :: 'MonadState' a m             => 'Control.Lens.Iso.Iso' a a c d       -> (c -> (e, d) -> m e--- ('%%=') :: 'MonadState' a m             => 'Lens' a a c d      -> (c -> (e, d) -> m e--- ('%%=') :: ('MonadState' a m, 'Monoid' e) => 'Control.Lens.Traversal.Traversal' a a c d -> (c -> (e, d) -> m e+-- t 'pure' ≡ 'pure'+-- 'fmap' (t f) '.' t g ≡ 'Data.Functor.Compose.getCompose' '.' t ('Data.Functor.Compose.Compose' '.' 'fmap' f '.' g) -- @-(%%=) :: MonadState a m => LensLike ((,) e) a a c d -> (c -> (e, d)) -> m e-#if MIN_VERSION_mtl(2,1,1)-l %%= f = State.state (l f)-#else-l %%= f = do-  (e, b) <- State.gets (l f)-  State.put b-  return e-#endif-{-# INLINE (%%=) #-}------------------------------------------------------------------------------------ Common Lenses--------------------------------------------------------------------------------+--+-- One consequence of this requirement is that a 'Traversal' needs to leave the same number of elements as a+-- candidate for subsequent 'Traversal' that it started with. Another testament to the strength of these laws+-- is that the caveat expressed in section 5.5 of the \"Essence of the Iterator Pattern\" about exotic+-- 'Data.Traversable.Traversable' instances that 'Data.Traversable.traverse' the same entry multiple times was actually already ruled out by the+-- second law in that same paper!+type Traversal s t a b = forall f. Applicative f => (a -> f b) -> s -> f t --- | This lens can be used to change the result of a function but only where--- the arguments match the key given.-resultAt :: Eq e => e -> Simple Lens (e -> a) a-resultAt e afa ea = go <$> afa a where-  a = ea e-  go a' e' | e == e'   = a'-           | otherwise = a-{-# INLINE resultAt #-}+-- | @+-- type 'Traversal'' = 'Simple' 'Traversal'+-- @+type Traversal' s a = Traversal s s a a --- | Merge two lenses, getters, setters, folds or traversals.------ @'chosen' ≡ 'choosing' 'id' 'id'@+-- | A 'Traversal' which targets at least one element. ----- @--- 'choosing' :: 'Control.Lens.Getter.Getter' a c           -> 'Control.Lens.Getter.Getter' b c           -> 'Control.Lens.Getter.Getter' ('Either' a b) c--- 'choosing' :: 'Control.Lens.Fold.Fold' a c             -> 'Control.Lens.Fold.Fold' b c             -> 'Control.Lens.Fold.Fold' ('Either' a b) c--- 'choosing' :: 'Simple' 'Lens' a c      -> 'Simple' 'Lens' b c      -> 'Simple' 'Lens' ('Either' a b) c--- 'choosing' :: 'Simple' 'Control.Lens.Traversal.Traversal' a c -> 'Simple' 'Control.Lens.Traversal.Traversal' b c -> 'Simple' 'Control.Lens.Traversal.Traversal' ('Either' a b) c--- 'choosing' :: 'Simple' 'Control.Lens.Setter.Setter' a c    -> 'Simple' 'Control.Lens.Setter.Setter' b c    -> 'Simple' 'Control.Lens.Setter.Setter' ('Either' a b) c--- @-choosing :: Functor f-       => LensLike f a b c c-       -> LensLike f a' b' c c-       -> LensLike f (Either a a') (Either b b') c c-choosing l _ f (Left a)   = Left <$> l f a-choosing _ r f (Right a') = Right <$> r f a'-{-# INLINE choosing #-}+-- Note that since 'Apply' is not a superclass of 'Applicative', a 'Traversal1'+-- cannot always be used in place of a 'Traversal'. In such circumstances+-- 'Control.Lens.Traversal.cloneTraversal' will convert a 'Traversal1' into a 'Traversal'.+type Traversal1 s t a b = forall f. Apply f => (a -> f b) -> s -> f t+type Traversal1' s a = Traversal1 s s a a --- | This is a 'Lens' that updates either side of an 'Either', where both sides have the same type.+-- | Every 'IndexedTraversal' is a valid 'Control.Lens.Traversal.Traversal' or+-- 'Control.Lens.Fold.IndexedFold'. ----- @'chosen' ≡ 'choosing' 'id' 'id'@+-- The 'Indexed' constraint is used to allow an 'IndexedTraversal' to be used+-- directly as a 'Control.Lens.Traversal.Traversal'. ----- >>> Left 12^.chosen--- 12--- >>> Right "hello"^.chosen--- "hello"--- >>> chosen *~ 10 $ Right 2--- Right 20-chosen :: Lens (Either a a) (Either b b) a b-chosen f (Left a) = Left <$> f a-chosen f (Right a) = Right <$> f a-{-# INLINE chosen #-}---- | 'alongside' makes a 'Lens' from two other lenses.+-- The 'Control.Lens.Traversal.Traversal' laws are still required to hold. ----- @'alongside' :: 'Lens' a b c d -> 'Lens' a' b' c' d' -> 'Lens' (a,a') (b,b') (c,c') (d,d')@-alongside :: LensLike (Context c d) a b c d-           -> LensLike (Context c' d')  a' b' c' d'-           -> Lens (a,a') (b,b') (c,c') (d,d')-alongside l r f (a, a') = case l (Context id) a of-  Context db c -> case r (Context id) a' of-    Context db' c' -> (\(d,d') -> (db d, db' d')) <$> f (c,c')-{-# INLINE alongside #-}+-- In addition, the index @i@ should satisfy the requirement that it stays+-- unchanged even when modifying the value @a@, otherwise traversals like+-- 'indices' break the 'Traversal' laws.+type IndexedTraversal i s t a b = forall p f. (Indexable i p, Applicative f) => p a (f b) -> s -> f t ----------------------------------------------------------------------------------- Cloning Lenses--------------------------------------------------------------------------------+-- | @+-- type 'IndexedTraversal'' i = 'Simple' ('IndexedTraversal' i)+-- @+type IndexedTraversal' i s a = IndexedTraversal i s s a a --- |--- Cloning a 'Lens' is one way to make sure you arent given--- something weaker, such as a 'Control.Lens.Traversal.Traversal' and can be--- used as a way to pass around lenses that have to be monomorphic in @f@.------ Note: This only accepts a proper 'Lens'.------ /\"Costate Comonad Coalgebra is equivalent of Java's member variable update technology for Haskell\"/ -- \@PLT_Borat on Twitter-cloneLens :: Functor f-  => LensLike (Context c d) a b c d-  -> (c -> f d) -> a -> f b-cloneLens f cfd a = case f (Context id) a of-  Context db c -> db <$> cfd c-{-# INLINE cloneLens #-}+type IndexedTraversal1 i s t a b = forall p f. (Indexable i p, Apply f) => p a (f b) -> s -> f t+type IndexedTraversal1' i s a = IndexedTraversal1 i s s a a ----------------------------------------------------------------------------------- Overloading function application--------------------------------------------------------------------------------+-- | An 'IndexPreservingTraversal' leaves any index it is composed with alone.+type IndexPreservingTraversal s t a b = forall p f. (Conjoined p, Applicative f) => p a (f b) -> p s (f t) --- | @type 'LensLike' f a b c d = 'Overloaded' (->) f a b c d@-type Overloaded k f a b c d = k (c -> f d) (a -> f b)+-- | @+-- type 'IndexPreservingTraversal'' = 'Simple' 'IndexPreservingTraversal'+-- @+type IndexPreservingTraversal' s a = IndexPreservingTraversal s s a a --- | @type 'SimpleOverloaded' k f a b = 'Simple' ('Overloaded' k f) a b@-type SimpleOverloaded k f a b = Overloaded k f a a b b+type IndexPreservingTraversal1 s t a b = forall p f. (Conjoined p, Apply f) => p a (f b) -> p s (f t)+type IndexPreservingTraversal1' s a = IndexPreservingTraversal1 s s a a ----------------------------------------------------------------------------------- Setting and Remembering--------------------------------------------------------------------------------+------------------------------------------------------------------------------+-- Setters+------------------------------------------------------------------------------ --- | Modify the target of a 'Lens' and return the result------ When you do not need the result of the addition, ('Control.Lens.Setter.%~') is more flexible.+-- | The only 'LensLike' law that can apply to a 'Setter' @l@ is that -- -- @--- ('<%~') ::             'Lens' a b c d      -> (c -> d) -> a -> (d, b)--- ('<%~') ::             'Control.Lens.Iso.Iso' a b c d       -> (c -> d) -> a -> (d, b)--- ('<%~') :: 'Monoid' d => 'Control.Lens.Traversal.Traversal' a b c d -> (c -> d) -> a -> (d, b)+-- 'Control.Lens.Setter.set' l y ('Control.Lens.Setter.set' l x a) ≡ 'Control.Lens.Setter.set' l y a -- @-(<%~) :: LensLike ((,)d) a b c d -> (c -> d) -> a -> (d, b)-l <%~ f = l $ \c -> let d = f c in (d, d)-{-# INLINE (<%~) #-}---- | Increment the target of a numerically valued 'Lens' and return the result ----- When you do not need the result of the addition, ('Control.Lens.Setter.+~') is more flexible.+-- You can't 'Control.Lens.Getter.view' a 'Setter' in general, so the other two laws are irrelevant. --+-- However, two 'Functor' laws apply to a 'Setter':+-- -- @--- ('<+~') :: 'Num' b => 'Simple' 'Lens' a b -> b -> a -> (b, a)--- ('<+~') :: 'Num' b => 'Simple' 'Control.Lens.Iso.Iso' a b  -> b -> a -> (b, a)+-- 'Control.Lens.Setter.over' l 'id' ≡ 'id'+-- 'Control.Lens.Setter.over' l f '.' 'Control.Lens.Setter.over' l g ≡ 'Control.Lens.Setter.over' l (f '.' g) -- @-(<+~) :: Num c => LensLike ((,)c) a b c c -> c -> a -> (c, b)-l <+~ c = l <%~ (+ c)-{-# INLINE (<+~) #-}---- | Decrement the target of a numerically valued 'Lens' and return the result ----- When you do not need the result of the subtraction, ('Control.Lens.Setter.-~') is more flexible.+-- These can be stated more directly: -- -- @--- ('<-~') :: 'Num' b => 'Simple' 'Lens' a b -> b -> a -> (b, a)--- ('<-~') :: 'Num' b => 'Simple' 'Control.Lens.Iso.Iso' a b  -> b -> a -> (b, a)+-- l 'pure' ≡ 'pure'+-- l f '.' 'untainted' '.' l g ≡ l (f '.' 'untainted' '.' g) -- @-(<-~) :: Num c => LensLike ((,)c) a b c c -> c -> a -> (c, b)-l <-~ c = l <%~ subtract c-{-# INLINE (<-~) #-}+--+-- You can compose a 'Setter' with a 'Lens' or a 'Traversal' using ('.') from the @Prelude@+-- and the result is always only a 'Setter' and nothing more.+--+-- >>> over traverse f [a,b,c,d]+-- [f a,f b,f c,f d]+--+-- >>> over _1 f (a,b)+-- (f a,b)+--+-- >>> over (traverse._1) f [(a,b),(c,d)]+-- [(f a,b),(f c,d)]+--+-- >>> over both f (a,b)+-- (f a,f b)+--+-- >>> over (traverse.both) f [(a,b),(c,d)]+-- [(f a,f b),(f c,f d)]+type Setter s t a b = forall f. Settable f => (a -> f b) -> s -> f t --- | Multiply the target of a numerically valued 'Lens' and return the result+-- | A 'Setter'' is just a 'Setter' that doesn't change the types. ----- When you do not need the result of the multiplication, ('Control.Lens.Setter.*~') is more--- flexible.+-- These are particularly common when talking about monomorphic containers. /e.g./ -- -- @--- ('<*~') :: 'Num' b => 'Simple' 'Lens' a b -> b -> a -> (b, a)--- ('<*~') :: 'Num' b => 'Simple' 'Control.Lens.Iso.Iso' a b  -> b -> a -> (b, a)+-- 'sets' Data.Text.map :: 'Setter'' 'Data.Text.Internal.Text' 'Char' -- @-(<*~) :: Num c => LensLike ((,)c) a b c c -> c -> a -> (c, b)-l <*~ c = l <%~ (* c)-{-# INLINE (<*~) #-}---- | Divide the target of a fractionally valued 'Lens' and return the result. ----- When you do not need the result of the division, ('Control.Lens.Setter.//~') is more flexible.--- -- @--- ('<//~') :: 'Fractional' b => 'Simple' 'Lens' a b -> b -> a -> (b, a)--- ('<//~') :: 'Fractional' b => 'Simple' 'Control.Lens.Iso.Iso' a b  -> b -> a -> (b, a)+-- type 'Setter'' = 'Simple' 'Setter' -- @-(<//~) :: Fractional c => LensLike ((,)c) a b c c -> c -> a -> (c, b)-l <//~ c = l <%~ (/ c)-{-# INLINE (<//~) #-}+type Setter' s a = Setter s s a a --- | Raise the target of a numerically valued 'Lens' to a non-negative--- 'Integral' power and return the result------ When you do not need the result of the division, ('Control.Lens.Setter.^~') is more flexible.+-- | Every 'IndexedSetter' is a valid 'Setter'. --+-- The 'Setter' laws are still required to hold.+type IndexedSetter i s t a b = forall f p.+  (Indexable i p, Settable f) => p a (f b) -> s -> f t++-- | @+-- type 'IndexedSetter'' i = 'Simple' ('IndexedSetter' i) -- @--- ('<^~') :: ('Num' b, 'Integral' c) => 'Simple' 'Lens' a b -> c -> a -> (b, a)--- ('<^~') :: ('Num' b, 'Integral' c) => 'Simple' 'Control.Lens.Iso.Iso' a b  -> c -> a -> (b, a)+type IndexedSetter' i s a = IndexedSetter i s s a a++-- | An 'IndexPreservingSetter' can be composed with a 'IndexedSetter', 'IndexedTraversal' or 'IndexedLens'+-- and leaves the index intact, yielding an 'IndexedSetter'.+type IndexPreservingSetter s t a b = forall p f. (Conjoined p, Settable f) => p a (f b) -> p s (f t)++-- | @+-- type 'IndexedPreservingSetter'' i = 'Simple' 'IndexedPreservingSetter' -- @-(<^~) :: (Num c, Integral d) => LensLike ((,)c) a b c c -> d -> a -> (c, b)-l <^~ d = l <%~ (^ d)-{-# INLINE (<^~) #-}+type IndexPreservingSetter' s a = IndexPreservingSetter s s a a --- | Raise the target of a fractionally valued 'Lens' to an 'Integral' power--- and return the result.+-----------------------------------------------------------------------------+-- Isomorphisms+-----------------------------------------------------------------------------++-- | Isomorphism families can be composed with another 'Lens' using ('.') and 'id'. ----- When you do not need the result of the division, ('Control.Lens.Setter.^^~') is more flexible.+-- Since every 'Iso' is both a valid 'Lens' and a valid 'Prism', the laws for those types+-- imply the following laws for an 'Iso' 'f': -- -- @--- ('<^^~') :: ('Fractional' b, 'Integral' c) => 'Simple' 'Lens' a b -> c -> a -> (b, a)--- ('<^^~') :: ('Fractional' b, 'Integral' c) => 'Simple' 'Control.Lens.Iso.Iso' a b  -> c -> a -> (b, a)+-- f '.' 'Control.Lens.Iso.from' f ≡ 'id'+-- 'Control.Lens.Iso.from' f '.' f ≡ 'id' -- @-(<^^~) :: (Fractional c, Integral d) => LensLike ((,)c) a b c c -> d -> a -> (c, b)-l <^^~ d = l <%~ (^^ d)-{-# INLINE (<^^~) #-}+--+-- Note: Composition with an 'Iso' is index- and measure- preserving.+type Iso s t a b = forall p f. (Profunctor p, Functor f) => p a (f b) -> p s (f t) --- | Raise the target of a floating-point valued 'Lens' to an arbitrary power--- and return the result.+-- | @+-- type 'Iso'' = 'Control.Lens.Type.Simple' 'Iso'+-- @+type Iso' s a = Iso s s a a++------------------------------------------------------------------------------+-- Review Internals+------------------------------------------------------------------------------++-- | This is a limited form of a 'Prism' that can only be used for 're' operations. ----- When you do not need the result of the division, ('Control.Lens.Setter.**~') is more flexible.+-- Like with a 'Getter', there are no laws to state for a 'Review'. --+-- You can generate a 'Review' by using 'unto'. You can also use any 'Prism' or 'Iso'+-- directly as a 'Review'.+type Review t b = forall p f. (Choice p, Bifunctor p, Settable f) => Optic' p f t b++-- | If you see this in a signature for a function, the function is expecting a 'Review'+-- (in practice, this usually means a 'Prism').+type AReview t b = Optic' Tagged Identity t b++------------------------------------------------------------------------------+-- Prism Internals+------------------------------------------------------------------------------++-- | A 'Prism' @l@ is a 'Traversal' that can also be turned+-- around with 'Control.Lens.Review.re' to obtain a 'Getter' in the+-- opposite direction.+--+-- There are three laws that a 'Prism' should satisfy:+--+-- First, if I 'Control.Lens.Review.re' or 'Control.Lens.Review.review' a value with a 'Prism' and then 'Control.Lens.Fold.preview' or use ('Control.Lens.Fold.^?'), I will get it back:+-- -- @--- ('<**~') :: 'Floating' b => 'Simple' 'Lens' a b -> b -> a -> (b, a)--- ('<**~') :: 'Floating' b => 'Simple' 'Control.Lens.Iso.Iso' a b  -> b -> a -> (b, a)+-- 'Control.Lens.Fold.preview' l ('Control.Lens.Review.review' l b) ≡ 'Just' b -- @-(<**~) :: Floating c => LensLike ((,)c) a b c c -> c -> a -> (c, b)-l <**~ c = l <%~ (** c)-{-# INLINE (<**~) #-}---- | Logically '||' a Boolean valued 'Lens' and return the result ----- When you do not need the result of the operation, ('Control.Lens.Setter.||~') is more flexible.+-- Second, if you can extract a value @a@ using a 'Prism' @l@ from a value @s@, then the value @s@ is completely described by @l@ and @a@: -- -- @--- ('<||~') :: 'Simple' 'Lens' a 'Bool' -> 'Bool' -> a -> ('Bool', a)--- ('<||~') :: 'Simple' 'Control.Lens.Iso.Iso' a 'Bool'  -> 'Bool' -> a -> ('Bool', a)+-- 'Control.Lens.Fold.preview' l s ≡ 'Just' a ⟹ 'Control.Lens.Review.review' l a ≡ s -- @-(<||~) :: LensLike ((,)Bool) a b Bool Bool -> Bool -> a -> (Bool, b)-l <||~ c = l <%~ (|| c)-{-# INLINE (<||~) #-}---- | Logically '&&' a Boolean valued 'Lens' and return the result ----- When you do not need the result of the operation, ('Control.Lens.Setter.&&~') is more flexible.+-- Third, if you get non-match @t@, you can convert it result back to @s@: -- -- @--- ('<&&~') :: 'Simple' 'Lens' a 'Bool' -> 'Bool' -> a -> ('Bool', a)--- ('<&&~') :: 'Simple' 'Control.Lens.Iso.Iso' a 'Bool'  -> 'Bool' -> a -> ('Bool', a)+-- 'Control.Lens.Combinators.matching' l s ≡ 'Left' t ⟹ 'Control.Lens.Combinators.matching' l t ≡ 'Left' s -- @-(<&&~) :: LensLike ((,)Bool) a b Bool Bool -> Bool -> a -> (Bool, b)-l <&&~ c = l <%~ (&& c)-{-# INLINE (<&&~) #-}---- | Modify the target of a 'Lens', but return the old value. ----- When you do not need the result of the addition, ('Control.Lens.Setter.%~') is more flexible.+-- The first two laws imply that the 'Traversal' laws hold for every 'Prism' and that we 'Data.Traversable.traverse' at most 1 element: -- -- @--- ('<<%~') ::             'Lens' a b c d      -> (c -> d) -> a -> (d, b)--- ('<<%~') ::             'Control.Lens.Iso.Iso' a b c d       -> (c -> d) -> a -> (d, b)--- ('<<%~') :: 'Monoid' d => 'Control.Lens.Traversal.Traversal' a b c d -> (c -> d) -> a -> (d, b)+-- 'Control.Lens.Fold.lengthOf' l x '<=' 1 -- @-(<<%~) :: LensLike ((,)c) a b c d -> (c -> d) -> a -> (c, b)-l <<%~ f = l $ \c -> (c, f c)-{-# INLINE (<<%~) #-}---- | Modify the target of a 'Lens', but return the old value. ----- When you do not need the old value, ('Control.Lens.Setter.%~') is more flexible.+-- It may help to think of this as an 'Iso' that can be partial in one direction. --+-- Every 'Prism' is a valid 'Traversal'.+--+-- Every 'Iso' is a valid 'Prism'.+--+-- For example, you might have a @'Prism'' 'Integer' 'Numeric.Natural.Natural'@ allows you to always+-- go from a 'Numeric.Natural.Natural' to an 'Integer', and provide you with tools to check if an 'Integer' is+-- a 'Numeric.Natural.Natural' and/or to edit one if it is.+--+-- -- @--- ('<<%~') ::             'Lens' a b c d      -> d -> a -> (c, b)--- ('<<%~') ::             'Control.Lens.Iso.Iso' a b c d       -> d -> a -> (c, b)--- ('<<%~') :: 'Monoid' d => 'Control.Lens.Traversal.Traversal' a b c d -> d -> a -> (c, b)+-- 'nat' :: 'Prism'' 'Integer' 'Numeric.Natural.Natural'+-- 'nat' = 'Control.Lens.Prism.prism' 'toInteger' '$' \\ i ->+--    if i '<' 0+--    then 'Left' i+--    else 'Right' ('fromInteger' i) -- @-(<<.~) :: LensLike ((,)c) a b c d -> d -> a -> (c, b)-l <<.~ d = l $ \c -> (c, d)-{-# INLINE (<<.~) #-}+--+-- Now we can ask if an 'Integer' is a 'Numeric.Natural.Natural'.+--+-- >>> 5^?nat+-- Just 5+--+-- >>> (-5)^?nat+-- Nothing+--+-- We can update the ones that are:+--+-- >>> (-3,4) & both.nat *~ 2+-- (-3,8)+--+-- And we can then convert from a 'Numeric.Natural.Natural' to an 'Integer'.+--+-- >>> 5 ^. re nat -- :: Natural+-- 5+--+-- Similarly we can use a 'Prism' to 'Data.Traversable.traverse' the 'Left' half of an 'Either':+--+-- >>> Left "hello" & _Left %~ length+-- Left 5+--+-- or to construct an 'Either':+--+-- >>> 5^.re _Left+-- Left 5+--+-- such that if you query it with the 'Prism', you will get your original input back.+--+-- >>> 5^.re _Left ^? _Left+-- Just 5+--+-- Another interesting way to think of a 'Prism' is as the categorical dual of a 'Lens'+-- -- a co-'Lens', so to speak. This is what permits the construction of 'Control.Lens.Prism.outside'.+--+-- Note: Composition with a 'Prism' is index-preserving.+type Prism s t a b = forall p f. (Choice p, Applicative f) => p a (f b) -> p s (f t) +-- | A 'Simple' 'Prism'.+type Prism' s a = Prism s s a a+ ---------------------------------------------------------------------------------- Setting and Remembering State+-- Equality ------------------------------------------------------------------------------- --- | Modify the target of a 'Lens' into your monad's state by a user supplied--- function and return the result.+-- | A witness that @(a ~ s, b ~ t)@. ----- When applied to a 'Control.Lens.Traversal.Traversal', it this will return a monoidal summary of all of the intermediate--- results.+-- Note: Composition with an 'Equality' is index-preserving.+type Equality (s :: k1) (t :: k2) (a :: k1) (b :: k2) = forall k3 (p :: k1 -> k3 -> Type) (f :: k2 -> k3) .+    p a (f b) -> p s (f t)++-- | A 'Simple' 'Equality'.+type Equality' s a = Equality s s a a++-- | Composable `asTypeOf`. Useful for constraining excess+-- polymorphism, @foo . (id :: As Int) . bar@.+type As a = Equality' a a++-------------------------------------------------------------------------------+-- Getters+-------------------------------------------------------------------------------++-- | A 'Getter' describes how to retrieve a single value in a way that can be+-- composed with other 'LensLike' constructions. ----- When you do not need the result of the operation, ('Control.Lens.Setter.%=') is more flexible.+-- Unlike a 'Lens' a 'Getter' is read-only. Since a 'Getter'+-- cannot be used to write back there are no 'Lens' laws that can be applied to+-- it. In fact, it is isomorphic to an arbitrary function from @(s -> a)@. ----- @--- ('<%=') :: 'MonadState' a m             => 'Simple' 'Lens' a b     -> (b -> b) -> m b--- ('<%=') :: 'MonadState' a m             => 'Simple' 'Control.Lens.Iso.Iso' a b      -> (b -> b) -> m b--- ('<%=') :: ('MonadState' a m, 'Monoid' b) => 'Simple' 'Traveral' a b -> (b -> b) -> m b--- @-(<%=) :: MonadState a m => LensLike ((,)d) a a c d -> (c -> d) -> m d-l <%= f = l %%= \c -> let d = f c in (d,d)-{-# INLINE (<%=) #-}+-- Moreover, a 'Getter' can be used directly as a 'Control.Lens.Fold.Fold',+-- since it just ignores the 'Applicative'.+type Getter s a = forall f. (Contravariant f, Functor f) => (a -> f a) -> s -> f s +-- | Every 'IndexedGetter' is a valid 'Control.Lens.Fold.IndexedFold' and can be used for 'Control.Lens.Getter.Getting' like a 'Getter'.+type IndexedGetter i s a = forall p f. (Indexable i p, Contravariant f, Functor f) => p a (f a) -> s -> f s --- | Add to the target of a numerically valued 'Lens' into your monad's state--- and return the result.+-- | An 'IndexPreservingGetter' can be used as a 'Getter', but when composed with an 'IndexedTraversal',+-- 'IndexedFold', or 'IndexedLens' yields an 'IndexedFold', 'IndexedFold' or 'IndexedGetter' respectively.+type IndexPreservingGetter s a = forall p f. (Conjoined p, Contravariant f, Functor f) => p a (f a) -> p s (f s)++--------------------------+-- Folds+--------------------------++-- | A 'Fold' describes how to retrieve multiple values in a way that can be composed+-- with other 'LensLike' constructions. ----- When you do not need the result of the multiplication, ('Control.Lens.Setter.+=') is more--- flexible.+-- A @'Fold' s a@ provides a structure with operations very similar to those of the 'Data.Foldable.Foldable'+-- typeclass, see 'Control.Lens.Fold.foldMapOf' and the other 'Fold' combinators. ----- @--- ('<+=') :: ('MonadState' a m, 'Num' b) => 'Simple' 'Lens' a b -> b -> m b--- ('<+=') :: ('MonadState' a m, 'Num' b) => 'Simple' 'Control.Lens.Iso.Iso' a b  -> b -> m b--- @-(<+=) :: (MonadState a m, Num b) => SimpleLensLike ((,)b) a b -> b -> m b-l <+= b = l <%= (+ b)-{-# INLINE (<+=) #-}---- | Subtract from the target of a numerically valued 'Lens' into your monad's--- state and return the result.+-- By convention, if there exists a 'foo' method that expects a @'Data.Foldable.Foldable' (f a)@, then there should be a+-- @fooOf@ method that takes a @'Fold' s a@ and a value of type @s@. ----- When you do not need the result of the multiplication, ('Control.Lens.Setter.-=') is more--- flexible.+-- A 'Getter' is a legal 'Fold' that just ignores the supplied 'Data.Monoid.Monoid'. ----- @--- ('<-=') :: ('MonadState' a m, 'Num' b) => 'Simple' 'Lens' a b -> b -> m b--- ('<-=') :: ('MonadState' a m, 'Num' b) => 'Simple' 'Control.Lens.Iso.Iso' a b  -> b -> m b--- @-(<-=) :: (MonadState a m, Num b) => SimpleLensLike ((,)b) a b -> b -> m b-l <-= b = l <%= subtract b-{-# INLINE (<-=) #-}+-- Unlike a 'Control.Lens.Traversal.Traversal' a 'Fold' is read-only. Since a 'Fold' cannot be used to write back+-- there are no 'Lens' laws that apply.+type Fold s a = forall f. (Contravariant f, Applicative f) => (a -> f a) -> s -> f s --- | Multiply the target of a numerically valued 'Lens' into your monad's--- state and return the result.------ When you do not need the result of the multiplication, ('Control.Lens.Setter.*=') is more--- flexible.+-- | Every 'IndexedFold' is a valid 'Control.Lens.Fold.Fold' and can be used for 'Control.Lens.Getter.Getting'.+type IndexedFold i s a = forall p f.  (Indexable i p, Contravariant f, Applicative f) => p a (f a) -> s -> f s++-- | An 'IndexPreservingFold' can be used as a 'Fold', but when composed with an 'IndexedTraversal',+-- 'IndexedFold', or 'IndexedLens' yields an 'IndexedFold' respectively.+type IndexPreservingFold s a = forall p f. (Conjoined p, Contravariant f, Applicative f) => p a (f a) -> p s (f s)++-- | A relevant Fold (aka 'Fold1') has one or more targets.+type Fold1 s a = forall f. (Contravariant f, Apply f) => (a -> f a) -> s -> f s+type IndexedFold1 i s a = forall p f.  (Indexable i p, Contravariant f, Apply f) => p a (f a) -> s -> f s+type IndexPreservingFold1 s a = forall p f. (Conjoined p, Contravariant f, Apply f) => p a (f a) -> p s (f s)++-------------------------------------------------------------------------------+-- Simple Overloading+-------------------------------------------------------------------------------++-- | A 'Simple' 'Lens', 'Simple' 'Traversal', ... can+-- be used instead of a 'Lens','Traversal', ...+-- whenever the type variables don't change upon setting a value. -- -- @--- ('<*=') :: ('MonadState' a m, 'Num' b) => 'Simple' 'Lens' a b -> b -> m b--- ('<*=') :: ('MonadState' a m, 'Num' b) => 'Simple' 'Control.Lens.Iso.Iso' a b  -> b -> m b+-- 'Data.Complex.Lens._imagPart' :: 'Simple' 'Lens' ('Data.Complex.Complex' a) a+-- 'Control.Lens.Traversal.traversed' :: 'Simple' ('IndexedTraversal' 'Int') [a] a -- @-(<*=) :: (MonadState a m, Num b) => SimpleLensLike ((,)b) a b -> b -> m b-l <*= b = l <%= (* b)-{-# INLINE (<*=) #-}---- | Divide the target of a fractionally valued 'Lens' into your monad's state--- and return the result. ----- When you do not need the result of the division, ('Control.Lens.Setter.//=') is more flexible.+-- Note: To use this alias in your own code with @'LensLike' f@ or+-- 'Setter', you may have to turn on @LiberalTypeSynonyms@. ----- @--- ('<//=') :: ('MonadState' a m, 'Fractional' b) => 'Simple' 'Lens' a b -> b -> m b--- ('<//=') :: ('MonadState' a m, 'Fractional' b) => 'Simple' 'Control.Lens.Iso.Iso' a b  -> b -> m b--- @-(<//=) :: (MonadState a m, Fractional b) => SimpleLensLike ((,)b) a b -> b -> m b-l <//= b = l <%= (/ b)-{-# INLINE (<//=) #-}+-- This is commonly abbreviated as a \"prime\" marker, /e.g./ 'Lens'' = 'Simple' 'Lens'.+type Simple f s a = f s s a a --- | Raise the target of a numerically valued 'Lens' into your monad's state--- to a non-negative 'Integral' power and return the result.------ When you do not need the result of the operation, ('Control.Lens.Setter.**=') is more flexible.+-------------------------------------------------------------------------------+-- Optics+-------------------------------------------------------------------------------++-- | A valid 'Optic' @l@ should satisfy the laws: -- -- @--- ('<^=') :: ('MonadState' a m, 'Num' b, 'Integral' c) => 'Simple' 'Lens' a b -> c -> m b--- ('<^=') :: ('MonadState' a m, 'Num' b, 'Integral' c) => 'Simple' 'Control.Lens.Iso.Iso' a b  -> c -> m b+-- l 'pure' ≡ 'pure'+-- l ('Procompose' f g) = 'Procompose' (l f) (l g) -- @-(<^=) :: (MonadState a m, Num b, Integral c) => SimpleLensLike ((,)b) a b -> c -> m b-l <^= c = l <%= (^ c)-{-# INLINE (<^=) #-}---- | Raise the target of a fractionally valued 'Lens' into your monad's state--- to an 'Integral' power and return the result. ----- When you do not need the result of the operation, ('Control.Lens.Setter.^^=') is more flexible.+-- This gives rise to the laws for 'Equality', 'Iso', 'Prism', 'Lens',+-- 'Traversal', 'Traversal1', 'Setter', 'Fold', 'Fold1', and 'Getter' as well+-- along with their index-preserving variants. -- -- @--- ('<^^=') :: ('MonadState' a m, 'Fractional' b, 'Integral' c) => 'Simple' 'Lens' a b -> c -> m b--- ('<^^=') :: ('MonadState' a m, 'Fractional' b, 'Integral' c) => 'Simple' 'Control.Lens.Iso.Iso' a b  -> c -> m b+-- type 'LensLike' f s t a b = 'Optic' (->) f s t a b -- @-(<^^=) :: (MonadState a m, Fractional b, Integral c) => SimpleLensLike ((,)b) a b -> c -> m b-l <^^= c = l <%= (^^ c)-{-# INLINE (<^^=) #-}+type Optic p f s t a b = p a (f b) -> p s (f t) --- | Raise the target of a floating-point valued 'Lens' into your monad's--- state to an arbitrary power and return the result.------ When you do not need the result of the operation, ('Control.Lens.Setter.**=') is more flexible.------ @--- ('<**=') :: ('MonadState' a m, 'Floating' b) => 'Simple' 'Lens' a b -> b -> m b--- ('<**=') :: ('MonadState' a m, 'Floating' b) => 'Simple' 'Control.Lens.Iso.Iso' a b  -> b -> m b+-- | @+-- type 'Optic'' p f s a = 'Simple' ('Optic' p f) s a -- @-(<**=) :: (MonadState a m, Floating b) => SimpleLensLike ((,)b) a b -> b -> m b-l <**= b = l <%= (** b)-{-# INLINE (<**=) #-}+type Optic' p f s a = Optic p f s s a a --- | Logically '||' a Boolean valued 'Lens' into your monad's state and return--- the result.------ When you do not need the result of the operation, ('Control.Lens.Setter.||=') is more flexible.+-- | @+-- type 'LensLike' f s t a b = 'Optical' (->) (->) f s t a b+-- @ -- -- @--- ('<||=') :: 'MonadState' a m => 'Simple' 'Lens' a 'Bool' -> 'Bool' -> m 'Bool'--- ('<||=') :: 'MonadState' a m => 'Simple' 'Control.Lens.Iso.Iso' a 'Bool'  -> 'Bool' -> m 'Bool'+-- type 'Over' p f s t a b = 'Optical' p (->) f s t a b -- @-(<||=) :: MonadState a m => SimpleLensLike ((,)Bool) a Bool -> Bool -> m Bool-l <||= b = l <%= (|| b)-{-# INLINE (<||=) #-}---- | Logically '&&' a Boolean valued 'Lens' into your monad's state and return--- the result. ----- When you do not need the result of the operation, ('Control.Lens.Setter.&&=') is more flexible.--- -- @--- ('<&&=') :: 'MonadState' a m => 'Simple' 'Lens' a 'Bool' -> 'Bool' -> m 'Bool'--- ('<&&=') :: 'MonadState' a m => 'Simple' 'Control.Lens.Iso.Iso' a 'Bool'  -> 'Bool' -> m 'Bool'+-- type 'Optic' p f s t a b = 'Optical' p p f s t a b -- @-(<&&=) :: MonadState a m => SimpleLensLike ((,)Bool) a Bool -> Bool -> m Bool-l <&&= b = l <%= (&& b)-{-# INLINE (<&&=) #-}+type Optical p q f s t a b = p a (f b) -> q s (f t) --- | Modify the target of a 'Lens' into your monad's state by a user supplied--- function and return the /old/ value that was replaced.------ When applied to a 'Control.Lens.Traversal.Traversal', it this will return a monoidal summary of all of the old values--- present.------ When you do not need the result of the operation, ('Control.Lens.Setter.%=') is more flexible.------ @--- ('<<%=') :: 'MonadState' a m             => 'Simple' 'Lens' a b     -> (b -> b) -> m b--- ('<<%=') :: 'MonadState' a m             => 'Simple' 'Control.Lens.Iso.Iso' a b      -> (b -> b) -> m b--- ('<<%=') :: ('MonadState' a m, 'Monoid' b) => 'Simple' 'Traveral' a b -> (b -> b) -> m b+-- | @+-- type 'Optical'' p q f s a = 'Simple' ('Optical' p q f) s a -- @-(<<%=) :: MonadState a m => LensLike ((,)c) a a c d -> (c -> d) -> m c-l <<%= f = l %%= \c -> (c, f c)-{-# INLINE (<<%=) #-}+type Optical' p q f s a = Optical p q f s s a a --- | Modify the target of a 'Lens' into your monad's state by a user supplied--- function and return the /old/ value that was replaced.++-- | Many combinators that accept a 'Lens' can also accept a+-- 'Traversal' in limited situations. ----- When applied to a 'Control.Lens.Traversal.Traversal', it this will return a monoidal summary of all of the old values--- present.+-- They do so by specializing the type of 'Functor' that they require of the+-- caller. ----- When you do not need the result of the operation, ('Control.Lens.Setter.%=') is more flexible.+-- If a function accepts a @'LensLike' f s t a b@ for some 'Functor' @f@,+-- then they may be passed a 'Lens'. ----- @--- ('<<%=') :: 'MonadState' a m             => 'Simple' 'Lens' a b     -> (b -> b) -> m b--- ('<<%=') :: 'MonadState' a m             => 'Simple' 'Control.Lens.Iso.Iso' a b      -> (b -> b) -> m b--- ('<<%=') :: ('MonadState' a m, 'Monoid' b) => 'Simple' 'Traveral' a b -> (b -> b) -> m b+-- Further, if @f@ is an 'Applicative', they may also be passed a+-- 'Traversal'.+type LensLike f s t a b = (a -> f b) -> s -> f t++-- | @+-- type 'LensLike'' f = 'Simple' ('LensLike' f) -- @-(<<.=) :: MonadState a m => LensLike ((,)c) a a c d -> d -> m c-l <<.= d = l %%= \c -> (c,d)-{-# INLINE (<<.=) #-}+type LensLike' f s a = LensLike f s s a a --- | Useful for storing lenses in containers.-newtype ReifiedLens a b c d = ReifyLens { reflectLens :: Lens a b c d }+-- | Convenient alias for constructing indexed lenses and their ilk.+type IndexedLensLike i f s t a b = forall p. Indexable i p => p a (f b) -> s -> f t --- | @type 'SimpleReifiedLens' = 'Simple' 'ReifiedLens'@-type SimpleReifiedLens a b = ReifiedLens a a b b+-- | Convenient alias for constructing simple indexed lenses and their ilk.+type IndexedLensLike' i f s a = IndexedLensLike i f s s a a++-- | This is a convenient alias for use when you need to consume either indexed or non-indexed lens-likes based on context.+type Over p f s t a b = p a (f b) -> s -> f t++-- | This is a convenient alias for use when you need to consume either indexed or non-indexed lens-likes based on context.+--+-- @+-- type 'Over'' p f = 'Simple' ('Over' p f)+-- @+type Over' p f s a = Over p f s s a a
+ src/Control/Lens/Unsound.hs view
@@ -0,0 +1,101 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE RankNTypes #-}++{-# OPTIONS_GHC -Wno-warnings-deprecations #-}++-------------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Unsound+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  Rank2Types+--+-- One commonly asked question is: can we combine two lenses,+-- @'Lens'' a b@ and @'Lens'' a c@ into @'Lens'' a (b, c)@.+-- This is fair thing to ask, but such operation is unsound in general.+-- See `lensProduct`.+--+-------------------------------------------------------------------------------+module Control.Lens.Unsound+  (+    lensProduct+  , prismSum+  , adjoin+  ) where++import Control.Lens+import Control.Lens.Internal.Prelude+import Prelude ()++-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens++-- | A lens product. There is no law-abiding way to do this in general.+-- Result is only a valid t'Lens' if the input lenses project disjoint parts of+-- the structure @s@. Otherwise "you get what you put in" law+--+-- @+-- 'Control.Lens.Getter.view' l ('Control.Lens.Setter.set' l v s) ≡ v+-- @+--+-- is violated by+--+-- >>> let badLens :: Lens' (Int, Char) (Int, Int); badLens = lensProduct _1 _1+-- >>> view badLens (set badLens (1,2) (3,'x'))+-- (2,2)+--+-- but we should get @(1,2)@.+--+-- Are you looking for 'Control.Lens.Lens.alongside'?+--+lensProduct :: ALens' s a -> ALens' s b -> Lens' s (a, b)+lensProduct l1 l2 f s =+    f (s ^# l1, s ^# l2) <&> \(a, b) -> s & l1 #~ a & l2 #~ b++-- | A dual of `lensProduct`: a prism sum.+--+-- The law+--+-- @+-- 'Control.Lens.Fold.preview' l ('Control.Lens.Review.review' l b) ≡ 'Just' b+-- @+--+-- breaks with+--+-- >>> let badPrism :: Prism' (Maybe Char) (Either Char Char); badPrism = prismSum _Just _Just+-- >>> preview badPrism (review badPrism (Right 'x'))+-- Just (Left 'x')+--+-- We put in 'Right' value, but get back 'Left'.+--+-- Are you looking for 'Control.Lens.Prism.without'?+--+prismSum :: APrism s t a b+         -> APrism s t c d+         -> Prism s t (Either a c) (Either b d)+prismSum k k' =+    withPrism k                  $ \bt seta ->+    withPrism k'                 $ \dt setb ->+    prism (either bt dt) $ \s ->+    f (Left <$> seta s) (Right <$> setb s)+  where+    f a@(Right _) _ = a+    f (Left _)    b = b++-- | A generalization of `mappend`ing folds: A union of disjoint traversals.+--+-- Traversing the same entry twice is illegal.+--+-- Are you looking for 'Control.Lens.Traversal.failing'?+--+adjoin :: Traversal' s a -> Traversal' s a -> Traversal' s a+adjoin t1 t2 =+    lensProduct (partsOf t1) (partsOf t2) . both . each
− src/Control/Lens/WithIndex.hs
@@ -1,455 +0,0 @@-{-# LANGUAGE CPP #-}-{-# LANGUAGE Rank2Types #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FunctionalDependencies #-}-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ > 706-{-# LANGUAGE DefaultSignatures #-}-#define MPTC_DEFAULTS-#endif----------------------------------------------------------------------------------- |--- Module      :  Control.Lens.WithIndex--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  Rank2Types------ (These need to be defined together for @DefaultSignatures@ to work.)---------------------------------------------------------------------------------module Control.Lens.WithIndex-  (-  -- * Indexed Functors-    FunctorWithIndex(..)-  , imapped-  -- * Indexed Foldables-  , FoldableWithIndex(..)-  , ifolded-  , ifolding-  -- ** Indexed Foldable Combinators-  , iany-  , iall-  , itraverse_-  , ifor_-  , imapM_-  , iforM_-  , iconcatMap-  , ifind-  , ifoldrM-  , ifoldlM-  , itoList-  -- * Converting to Folds-  , withIndices-  , indices-  -- * Indexed Traversables-  , TraversableWithIndex(..)-  , itraversed-  -- * Indexed Traversable Combinators-  , ifor-  , imapM-  , iforM-  , imapAccumR-  , imapAccumL-  , iwhere-  ) where--import Control.Applicative-import Control.Applicative.Backwards-import Control.Monad (void, liftM)-import Control.Monad.Trans.State.Lazy as Lazy-import Control.Lens.Fold-import Control.Lens.Internal-import Control.Lens.Indexed-import Control.Lens.IndexedSetter-import Control.Lens.IndexedFold-import Control.Lens.IndexedTraversal-import Data.Foldable-import Data.Hashable-import Data.HashMap.Lazy as HashMap-import Data.IntMap as IntMap-import Data.Map as Map-import Data.Monoid-import Data.Sequence hiding (index)-import Data.Traversable---- $setup--- >>> import Control.Lens------------------------------------------------------------------------------------ FunctorWithIndex------------------------------------------------------------------------------------ | A 'Functor' with an additional index.------ Instances must satisfy a modified form of the 'Functor' laws:------ @--- 'imap' f '.' 'imap' g ≡ 'imap' (\i -> f i . g i)--- 'imap' (\_ a -> a) ≡ 'id'--- @-class Functor f => FunctorWithIndex i f | f -> i where-  -- | Map with access to the index.-  imap :: (i -> a -> b) -> f a -> f b-#ifdef MPTC_DEFAULTS-  default imap :: TraversableWithIndex i f => (i -> a -> b) -> f a -> f b-  imap = imapOf itraversed-#endif---- | The 'IndexedSetter' for a 'FunctorWithIndex'.------ If you don't need access to the index, then 'mapped' is more flexible in what it accepts.-imapped :: FunctorWithIndex i f => IndexedSetter i (f a) (f b) a b-imapped = isets imap-{-# INLINE imapped #-}------------------------------------------------------------------------------------ FoldableWithIndex------------------------------------------------------------------------------------ | A container that supports folding with an additional index.-class Foldable f => FoldableWithIndex i f | f -> i where-  ---  -- |-  -- Fold a container by mapping value to an arbitrary 'Monoid' with access to the index @i@.-  ---  -- When you don't need access to the index then 'foldMap' is more flexible in what it accepts.-  ---  -- @'foldMap' ≡ 'ifoldMap' '.' 'const'@-  ifoldMap :: Monoid m => (i -> a -> m) -> f a -> m-#ifdef MPTC_DEFAULTS-  default ifoldMap :: (TraversableWithIndex i f, Monoid m) => (i -> a -> m) -> f a -> m-  ifoldMap = ifoldMapOf itraversed-  {-# INLINE ifoldMap #-}-#endif--  -- | Right-associative fold of an indexed container with access to the index @i@.-  ---  -- When you don't need access to the index then 'Data.Foldable.foldr' is more flexible in what it accepts.-  ---  -- @'Data.Foldable.foldr' ≡ 'ifoldr' '.' 'const'@-  ifoldr   :: (i -> a -> b -> b) -> b -> f a -> b-  ifoldr f z t = appEndo (ifoldMap (\i -> Endo . f i) t) z--  -- |-  -- Left-associative fold of an indexed container with access to the index @i@.-  ---  -- When you don't need access to the index then 'foldl' is more flexible in what it accepts.-  ---  -- @'foldl' ≡ 'ifoldl' '.' 'const'@-  ifoldl :: (i -> b -> a -> b) -> b -> f a -> b-  ifoldl f z t = appEndo (getDual (ifoldMap (\i -> Dual . Endo . flip (f i)) t)) z--  -- | /Strictly/ fold right over the elements of a structure with access to the index @i@.-  ---  -- When you don't need access to the index then 'foldr'' is more flexible in what it accepts.-  ---  -- @'foldr'' ≡ 'ifoldr'' '.' 'const'@-  ifoldr' :: (i -> a -> b -> b) -> b -> f a -> b-  ifoldr' f z0 xs = ifoldl f' id xs z0-    where f' i k x z = k $! f i x z--  -- | Fold over the elements of a structure with an index, associating to the left, but /strictly/.-  ---  -- When you don't need access to the index then 'Control.Lens.Fold.foldlOf'' is more flexible in what it accepts.-  ---  -- @'Control.Lens.Fold.foldlOf'' l ≡ 'ifoldlOf'' l '.' 'const'@-  ---  -- @-  -- 'ifoldlOf'' :: 'Control.Lens.IndexedGetter.IndexedGetter' i a c            -> (i -> e -> c -> e) -> e -> a -> e-  -- 'ifoldlOf'' :: 'IndexedFold' i a c              -> (i -> e -> c -> e) -> e -> a -> e-  -- 'ifoldlOf'' :: 'Control.Lens.IndexedLens.SimpleIndexedLens' i a c        -> (i -> e -> c -> e) -> e -> a -> e-  -- 'ifoldlOf'' :: 'Control.Lens.IndexedTraversal.SimpleIndexedTraversal' i a c   -> (i -> e -> c -> e) -> e -> a -> e-  -- @-  ifoldl' :: (i -> b -> a -> b) -> b -> f a -> b-  ifoldl' f z0 xs = ifoldr f' id xs z0-    where f' i x k z = k $! f i z x---- | The 'IndexedFold' of a 'FoldableWithIndex' container.-ifolded :: FoldableWithIndex i f => IndexedFold i (f a) a-ifolded = index $ \ f -> coerce . getFolding . ifoldMap (\i -> Folding . f i)-{-# INLINE ifolded #-}---- | Obtain a 'Fold' by lifting an operation that returns a foldable result.------ This can be useful to lift operations from @Data.List@ and elsewhere into a 'Fold'.-ifolding :: FoldableWithIndex i f => (a -> f c) -> IndexedFold i a c-ifolding afc = index $ \ icgd -> coerce . itraverse_ icgd . afc-{-# INLINE ifolding #-}---- |--- Return whether or not any element in a container satisfies a predicate, with access to the index @i@.------ When you don't need access to the index then 'any' is more flexible in what it accepts.------ @'any' = 'iany' '.' 'const'@-iany :: FoldableWithIndex i f => (i -> a -> Bool) -> f a -> Bool-iany f = getAny . ifoldMap (\i -> Any . f i)-{-# INLINE iany #-}---- |--- Return whether or not all elements in a container satisfy a predicate, with access to the index @i@.------ When you don't need access to the index then 'all' is more flexible in what it accepts.------ @'all' ≡ 'iall' '.' 'const'@-iall :: FoldableWithIndex i f => (i -> a -> Bool) -> f a -> Bool-iall f = getAll . ifoldMap (\i -> All . f i)-{-# INLINE iall #-}---- |--- Traverse elements with access to the index @i@, discarding the results.------ When you don't need access to the index then 'traverse_' is more flexible in what it accepts.------ @'traverse_' l = 'itraverse' '.' 'const'@-itraverse_ :: (FoldableWithIndex i t, Applicative f) => (i -> a -> f b) -> t a -> f ()-itraverse_ f = getTraversed . ifoldMap (\i -> Traversed . void . f i)-{-# INLINE itraverse_ #-}---- |--- Traverse elements with access to the index @i@, discarding the results (with the arguments flipped).------ @'ifor_' ≡ 'flip' 'itraverse_'@------ When you don't need access to the index then 'for_' is more flexible in what it accepts.------ @'for_' a ≡ 'ifor_' a '.' 'const'@-ifor_ :: (FoldableWithIndex i t, Applicative f) => t a -> (i -> a -> f b) -> f ()-ifor_ = flip itraverse_-{-# INLINE ifor_ #-}---- |--- Run monadic actions for each target of an 'IndexedFold' or 'Control.Lens.IndexedTraversal.IndexedTraversal' with access to the index,--- discarding the results.------ When you don't need access to the index then 'Control.Lens.Fold.mapMOf_' is more flexible in what it accepts.------ @'mapM_' ≡ 'imapM' '.' 'const'@-imapM_ :: (FoldableWithIndex i t, Monad m) => (i -> a -> m b) -> t a -> m ()-imapM_ f = getSequenced . ifoldMap (\i -> Sequenced . liftM skip . f i)-{-# INLINE imapM_ #-}---- |--- Run monadic actions for each target of an 'IndexedFold' or 'Control.Lens.IndexedTraversal.IndexedTraversal' with access to the index,--- discarding the results (with the arguments flipped).------ @'iforM_' ≡ 'flip' 'imapM_'@------ When you don't need access to the index then 'Control.Lens.Fold.forMOf_' is more flexible in what it accepts.------ @'Control.Lens.Fold.forMOf_' l a ≡ 'iforMOf' l a '.' 'const'@-iforM_ :: (FoldableWithIndex i t, Monad m) => t a -> (i -> a -> m b) -> m ()-iforM_ = flip imapM_-{-# INLINE iforM_ #-}---- |--- Concatenate the results of a function of the elements of an indexed container with access to the index.------ When you don't need access to the index then 'concatMap' is more flexible in what it accepts.------ @--- 'concatMap' ≡ 'iconcatMap' . 'const'--- 'iconcatMap' ≡ 'ifoldMap'--- @-iconcatMap :: FoldableWithIndex i f => (i -> a -> [b]) -> f a -> [b]-iconcatMap = ifoldMap-{-# INLINE iconcatMap #-}---- | Searches a container with a predicate that is also supplied the index, returning the left-most element of the structure--- matching the predicate, or 'Nothing' if there is no such element.------ When you don't need access to the index then 'find' is more flexible in what it accepts.------ @'find' ≡ 'ifind' '.' 'const'@-ifind :: FoldableWithIndex i f => (i -> a -> Bool) -> f a -> Maybe (i, a)-ifind p = getFirst . ifoldMap step where-  step i c-    | p i c     = First $ Just (i, c)-    | otherwise = First Nothing-{-# INLINE ifind #-}---- | Monadic fold right over the elements of a structure with an index.------ When you don't need access to the index then 'foldrM' is more flexible in what it accepts.------ @'foldrM' ≡ 'ifoldrM' '.' 'const'@-ifoldrM :: (FoldableWithIndex i f, Monad m) => (i -> a -> b -> m b) -> b -> f a -> m b-ifoldrM f z0 xs = ifoldl f' return xs z0-  where f' i k x z = f i x z >>= k-{-# INLINE ifoldrM #-}---- | Monadic fold over the elements of a structure with an index, associating to the left.------ When you don't need access to the index then 'foldlM' is more flexible in what it accepts.------ @'foldlM' ≡ 'ifoldlM' '.' 'const'@-ifoldlM :: (FoldableWithIndex i f, Monad m) => (i -> b -> a -> m b) -> b -> f a -> m b-ifoldlM f z0 xs = ifoldr f' return xs z0-  where f' i x k z = f i z x >>= k-{-# INLINE ifoldlM #-}---- | Extract the key-value pairs from a structure.------ When you don't need access to the indices in the result, then 'toList' is more flexible in what it accepts.------ @'toList' ≡ 'map' 'fst' '.' 'itoList'@-itoList :: FoldableWithIndex i f => f a -> [(i,a)]-itoList = ifoldr (\i c -> ((i,c):)) []-{-# INLINE itoList #-}------------------------------------------------------------------------------------ Converting to Folds------------------------------------------------------------------------------------ | Fold a container with indices returning both the indices and the values.-withIndices :: FoldableWithIndex i f => Fold (f a) (i,a)-withIndices f = coerce . getFolding . ifoldMap (\i a -> Folding (f (i,a)))-{-# INLINE withIndices #-}---- | Fold a container with indices returning only the indices.-indices :: FoldableWithIndex i f => Fold (f a) i-indices f = coerce . getFolding . ifoldMap (const . Folding . f)-{-# INLINE indices #-}------------------------------------------------------------------------------------ TraversableWithIndex------------------------------------------------------------------------------------ | A 'Traversable' with an additional index.------ An instance must satisfy a (modified) form of the 'Traversable' laws:------ @--- 'itraverse' ('const' 'Data.Functor.Identity.Identity') ≡ 'Data.Functor.Identity.Identity'--- 'fmap' ('itraverse' f) '.' 'itraverse' g ≡ 'getCompose' '.' 'itraverse' (\i -> 'Compose' '.' 'fmap' (f i) '.' g i)--- @-class (FunctorWithIndex i t, FoldableWithIndex i t, Traversable t) => TraversableWithIndex i t | t -> i where-  -- | Traverse an indexed container.-  itraverse :: Applicative f => (i -> a -> f b) -> t a -> f (t b)-#ifdef MPTC_DEFAULTS-  default itraverse :: Applicative f => (Int -> a -> f b) -> t a -> f (t b)-  itraverse = withIndex (indexed traverse)-  {-# INLINE itraverse #-}-#endif---- | The 'IndexedTraversal' of a 'TraversableWithIndex' container.-itraversed :: TraversableWithIndex i f => IndexedTraversal i (f a) (f b) a b-itraversed = index itraverse-{-# INLINE itraversed #-}---- |--- Traverse with an index (and the arguments flipped)------ @--- 'for' a ≡ 'ifor' a '.' 'const'--- 'ifor' ≡ 'flip' 'itraverse'--- @-ifor :: (TraversableWithIndex i t, Applicative f) => t a -> (i -> a -> f b) -> f (t b)-ifor = flip itraverse-{-# INLINE ifor #-}---- | Map each element of a structure to a monadic action,--- evaluate these actions from left to right, and collect the results, with access--- the index.------ When you don't need access to the index 'mapM' is more liberal in what it can accept.------ @'mapM' ≡ 'imapM' '.' 'const'@-imapM :: (TraversableWithIndex i t, Monad m) => (i -> a -> m b) -> t a -> m (t b)-imapM f = unwrapMonad . itraverse (\i -> WrapMonad . f i)-{-# INLINE imapM #-}---- | Map each element of a structure to a monadic action,--- evaluate these actions from left to right, and collect the results, with access--- its position (and the arguments flipped).------ @--- 'forM' a ≡ 'iforM' a '.' 'const'--- 'iforM' ≡ 'flip' 'imapM'--- @-iforM :: (TraversableWithIndex i t, Monad m) => t a -> (i -> a -> m b) -> m (t b)-iforM = flip imapM-{-# INLINE iforM #-}---- | Generalizes 'Data.Traversable.mapAccumR' to add access to the index.------ 'imapAccumROf' accumulates state from right to left.------ @'Control.Lens.Traversal.mapAccumR' ≡ 'imapAccumR' '.' 'const'@-imapAccumR :: TraversableWithIndex i t => (i -> s -> a -> (s, b)) -> s -> t a -> (s, t b)-imapAccumR f s0 a = swap (Lazy.runState (itraverse (\i c -> Lazy.state (\s -> swap (f i s c))) a) s0)-{-# INLINE imapAccumR #-}---- | Generalizes 'Data.Traversable.mapAccumL' to add access to the index.------ 'imapAccumLOf' accumulates state from left to right.------ @'Control.Lens.Traversal.mapAccumLOf' ≡ 'imapAccumL' '.' 'const'@-imapAccumL :: TraversableWithIndex i t => (i -> s -> a -> (s, b)) -> s -> t a -> (s, t b)-imapAccumL f s0 a = swap (Lazy.runState (forwards (itraverse (\i c -> Backwards (Lazy.state (\s -> swap (f i s c)))) a)) s0)-{-# INLINE imapAccumL #-}---- | Access the element of an indexed container where the index matches a predicate.------ >>> over (iwhere (>0)) Prelude.reverse $ ["He","was","stressed","o_O"]--- ["He","saw","desserts","O_o"]-iwhere :: (TraversableWithIndex i t) => (i -> Bool) -> SimpleIndexedTraversal i (t a) a-iwhere p = index $ \f a -> itraverse (\i c -> if p i then f i c else pure c) a-{-# INLINE iwhere #-}------------------------------------------------------------------------------------ Instances------------------------------------------------------------------------------------ | The position in the list is available as the index.-instance FunctorWithIndex Int [] where-  imap = imapOf itraversed-instance FoldableWithIndex Int [] where-  ifoldMap = ifoldMapOf itraversed-instance TraversableWithIndex Int [] where-  itraverse = withIndex (indexed traverse)---- | The position in the sequence is available as the index.-instance FunctorWithIndex Int Seq where-  imap = imapOf itraversed-instance FoldableWithIndex Int Seq where-  ifoldMap = ifoldMapOf itraversed-instance TraversableWithIndex Int Seq where-  itraverse = withIndex (indexed traverse)--instance FunctorWithIndex Int IntMap where-  imap = imapOf itraversed-instance FoldableWithIndex Int IntMap where-  ifoldMap = ifoldMapOf itraversed-instance TraversableWithIndex Int IntMap where-  itraverse f = sequenceA . IntMap.mapWithKey f-  {-# INLINE itraverse #-}--instance Ord k => FunctorWithIndex k (Map k) where-  imap = imapOf itraversed-instance Ord k => FoldableWithIndex k (Map k) where-  ifoldMap = ifoldMapOf itraversed-instance Ord k => TraversableWithIndex k (Map k) where-  itraverse f = sequenceA . Map.mapWithKey f-  {-# INLINE itraverse #-}--instance (Eq k, Hashable k) => FunctorWithIndex k (HashMap k) where-  imap = imapOf itraversed-instance (Eq k, Hashable k) => FoldableWithIndex k (HashMap k) where-  ifoldMap = ifoldMapOf itraversed-instance (Eq k, Hashable k) => TraversableWithIndex k (HashMap k) where-  itraverse = HashMap.traverseWithKey-  {-# INLINE itraverse #-}------------------------------------------------------------------------------------ Misc.----------------------------------------------------------------------------------swap :: (a,b) -> (b,a)-swap (a,b) = (b,a)-{-# INLINE swap #-}--skip :: a -> ()-skip _ = ()-{-# INLINE skip #-}
+ src/Control/Lens/Wrapped.hs view
@@ -0,0 +1,1384 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE DefaultSignatures #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-}++#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-}+#endif++#if !(MIN_VERSION_base(4,16,0)) || !MIN_VERSION_transformers(0,6,0)+{-# OPTIONS_GHC -Wno-warnings-deprecations #-}+#endif++#include "lens-common.h"++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Lens.Wrapped+-- Copyright   :  (C) 2012-16 Edward Kmett, Michael Sloan+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  Rank2, MPTCs, fundeps+--+-- The t'Wrapped' class provides similar functionality as @Control.Newtype@,+-- from the @newtype@ package, but in a more convenient and efficient form.+--+-- There are a few functions from @newtype@ that are not provided here, because+-- they can be done with the 'Iso' directly:+--+-- @+-- Control.Newtype.over 'Sum' f ≡ '_Unwrapping' 'Sum' 'Control.Lens.Setter.%~' f+-- Control.Newtype.under 'Sum' f ≡ '_Wrapping' 'Sum' 'Control.Lens.Setter.%~' f+-- Control.Newtype.overF 'Sum' f ≡ 'mapping' ('_Unwrapping' 'Sum') 'Control.Lens.Setter.%~' f+-- Control.Newtype.underF 'Sum' f ≡ 'mapping' ('_Wrapping' 'Sum') 'Control.Lens.Setter.%~' f+-- @+--+-- 'under' can also be used with '_Unwrapping' to provide the equivalent of+-- @Control.Newtype.under@.  Also, most use cases don't need full polymorphism,+-- so only the single constructor '_Wrapping' functions would be needed.+--+-- These equivalences aren't 100% honest, because @newtype@'s operators+-- need to rely on two @Newtype@ constraints.  This means that the wrapper used+-- for the output is not necessarily the same as the input.+--+----------------------------------------------------------------------------+module Control.Lens.Wrapped+  (+  -- * Wrapping and Unwrapping monomorphically+    Wrapped(..)+  , _Unwrapped'+  , _Wrapping', _Unwrapping'+  -- * Wrapping and unwrapping polymorphically+  , Rewrapped, Rewrapping+  , _Wrapped, _Unwrapped+  , _Wrapping, _Unwrapping+  -- * Operations+  , op+  , ala, alaf+  -- * Pattern Synonyms+  , pattern Wrapped+  , pattern Unwrapped+  -- * Generics+  , _GWrapped'+  ) where++#include "HsBaseConfig.h"++import qualified Control.Alternative.Free as Free+import qualified Control.Applicative as Applicative+import           Control.Applicative hiding (WrappedArrow(..))+import           Control.Applicative.Trans.Free+import           Control.Arrow+import           Control.Applicative.Backwards+import           Control.Comonad.Trans.Cofree+import           Control.Comonad.Trans.Coiter+import           Control.Comonad.Trans.Traced+import           Control.Exception+import           Control.Lens.Getter+import           Control.Lens.Internal.CTypes+import           Control.Lens.Iso+import           Control.Lens.Review+import           Control.Monad.Catch.Pure+import           Control.Monad.Trans.Cont+import           Control.Monad.Trans.Except+import           Control.Monad.Trans.Free+import           Control.Monad.Trans.Identity+import           Control.Monad.Trans.Iter+import           Control.Monad.Trans.Maybe+import           Control.Monad.Trans.Reader+import qualified Control.Monad.Trans.RWS.Lazy      as Lazy+import qualified Control.Monad.Trans.RWS.Strict    as Strict+import qualified Control.Monad.Trans.State.Lazy    as Lazy+import qualified Control.Monad.Trans.State.Strict  as Strict+import qualified Control.Monad.Trans.Writer.Lazy   as Lazy+import qualified Control.Monad.Trans.Writer.Strict as Strict+#if !MIN_VERSION_transformers(0,6,0)+import           Control.Monad.Trans.Error+import           Control.Monad.Trans.List+#endif+import           Data.Bifunctor.Biff+import           Data.Bifunctor.Clown+import           Data.Bifunctor.Fix+import           Data.Bifunctor.Flip+import           Data.Bifunctor.Join+import           Data.Bifunctor.Joker+import           Data.Bifunctor.Tannen+import           Data.Bifunctor.Wrapped+import           Data.Foldable as Foldable+import           Data.Functor.Bind+import           Data.Functor.Compose+import           Data.Functor.Contravariant+import qualified Data.Functor.Contravariant.Compose as Contravariant+import           Data.Functor.Constant+import           Data.Functor.Identity+import           Data.Functor.Reverse+import           Data.Hashable+import qualified Data.IntSet as IntSet+import           Data.IntSet (IntSet)+import qualified Data.IntMap as IntMap+import           Data.IntMap (IntMap)+import qualified Data.HashSet as HashSet+import           Data.HashSet (HashSet)+import qualified Data.HashMap.Lazy as HashMap+import           Data.HashMap.Lazy (HashMap)+import           Data.Kind+import           Data.List.NonEmpty (NonEmpty(..))+import qualified Data.Map as Map+import           Data.Map (Map)+import qualified Data.Monoid as Monoid+import           Data.Monoid+import qualified Data.Profunctor as Profunctor+import           Data.Profunctor hiding (WrappedArrow(..))+import           Data.Profunctor.Cayley+import qualified Data.Semigroup as S+import           Data.Semigroupoid+import qualified Data.Semigroupoid.Dual as Semigroupoid+import           Data.Semigroupoid.Static+import qualified Data.Sequence as Seq+import           Data.Sequence (Seq)+import qualified Data.Set as Set+import           Data.Set (Set)+import           Data.Tagged+import qualified Data.Vector as Vector+#if MIN_VERSION_vector(0,13,2)+import qualified Data.Vector.Strict as VectorStrict+#endif+import qualified Data.Vector.Primitive as Prim+import           Data.Vector.Primitive (Prim)+import qualified Data.Vector.Unboxed as Unboxed+import           Data.Vector.Unboxed (Unbox)+import qualified Data.Vector.Storable as Storable+import           Foreign.C.Error+import           Foreign.C.Types+import           Foreign.Storable (Storable)+import qualified GHC.Generics as Generic+import           GHC.Generics hiding (from, to)+import           System.Posix.Types+import           Data.Ord (Down(Down))++-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import Data.Foldable (foldMap)+-- >>> import Data.Monoid (Sum (..), Product (..), All (..), Any (..))++-- | t'Wrapped' provides isomorphisms to wrap and unwrap newtypes or+-- data types with one constructor.+class Wrapped s where+  type Unwrapped s :: Type+  type Unwrapped s = GUnwrapped (Rep s)++  -- | An isomorphism between @s@ and @a@.+  --+  -- If your type has a 'Generic' instance, '_Wrapped'' will default to '_GWrapped'',+  -- and you can choose to not override it with your own definition.+  _Wrapped' :: Iso' s (Unwrapped s)+  default _Wrapped' :: (Generic s, D1 d (C1 c (S1 s' (Rec0 a))) ~ Rep s, Unwrapped s ~ GUnwrapped (Rep s))+                    => Iso' s (Unwrapped s)+  _Wrapped' = _GWrapped'+  {-# INLINE _Wrapped' #-}++-- | Implement the '_Wrapped' operation for a type using its 'Generic' instance.+_GWrapped' :: (Generic s, D1 d (C1 c (S1 s' (Rec0 a))) ~ Rep s, Unwrapped s ~ GUnwrapped (Rep s))+           => Iso' s (Unwrapped s)+_GWrapped' = iso Generic.from Generic.to . iso remitter reviewer+  where+    remitter (M1 (M1 (M1 (K1 x)))) = x+    reviewer x = M1 (M1 (M1 (K1 x)))+{-# INLINE _GWrapped' #-}++type family GUnwrapped (rep :: Type -> Type) :: Type+type instance GUnwrapped (D1 d (C1 c (S1 s (Rec0 a)))) = a++pattern Wrapped :: Rewrapped s s => Unwrapped s -> s+pattern Wrapped a <- (view _Wrapped -> a) where+  Wrapped a = review _Wrapped a++pattern Unwrapped :: Rewrapped t t => t -> Unwrapped t+pattern Unwrapped a <- (view _Unwrapped -> a) where+  Unwrapped a = review _Unwrapped a++-- This can be used to help inference between the wrappers+class Wrapped s => Rewrapped (s :: Type) (t :: Type)++class    (Rewrapped s t, Rewrapped t s) => Rewrapping s t+instance (Rewrapped s t, Rewrapped t s) => Rewrapping s t++_Unwrapped' :: Wrapped s => Iso' (Unwrapped s) s+_Unwrapped' = from _Wrapped'+{-# INLINE _Unwrapped' #-}++-- | Work under a newtype wrapper.+--+-- >>> Const "hello" & _Wrapped %~ Prelude.length & getConst+-- 5+--+-- @+-- '_Wrapped'   ≡ 'from' '_Unwrapped'+-- '_Unwrapped' ≡ 'from' '_Wrapped'+-- @+_Wrapped :: Rewrapping s t => Iso s t (Unwrapped s) (Unwrapped t)+_Wrapped = withIso _Wrapped' $ \ sa _ -> withIso _Wrapped' $ \ _ bt -> iso sa bt+{-# INLINE _Wrapped #-}++_Unwrapped :: Rewrapping s t => Iso (Unwrapped t) (Unwrapped s) t s+_Unwrapped = from _Wrapped+{-# INLINE _Unwrapped #-}++-- * base++instance (t ~ All) => Rewrapped All t+instance Wrapped All where+  type Unwrapped All = Bool+  _Wrapped' = iso getAll All+  {-# INLINE _Wrapped' #-}++instance (t ~ Any) => Rewrapped Any t+instance Wrapped Any where+  type Unwrapped Any = Bool+  _Wrapped' = iso getAny Any+  {-# INLINE _Wrapped' #-}++instance (t ~ Sum b) => Rewrapped (Sum a) t+instance Wrapped (Sum a) where+  type Unwrapped (Sum a) = a+  _Wrapped' = iso getSum Sum+  {-# INLINE _Wrapped' #-}++instance (t ~ Product b) => Rewrapped (Product a) t+instance Wrapped (Product a) where+  type Unwrapped (Product a) = a+  _Wrapped' = iso getProduct Product+  {-# INLINE _Wrapped' #-}++instance (t ~ Kleisli m' a' b') => Rewrapped (Kleisli m a b) t+instance Wrapped (Kleisli m a b) where+  type Unwrapped (Kleisli m a b) = a -> m b+  _Wrapped' = iso runKleisli Kleisli+  {-# INLINE _Wrapped' #-}++instance (t ~ WrappedMonad m' a') => Rewrapped (WrappedMonad m a) t+instance Wrapped (WrappedMonad m a) where+  type Unwrapped (WrappedMonad m a) = m a+  _Wrapped' = iso unwrapMonad WrapMonad+  {-# INLINE _Wrapped' #-}++instance (t ~ Applicative.WrappedArrow a' b' c') => Rewrapped (Applicative.WrappedArrow a b c) t+instance Wrapped (Applicative.WrappedArrow a b c) where+  type Unwrapped (Applicative.WrappedArrow a b c) = a b c+  _Wrapped' = iso Applicative.unwrapArrow Applicative.WrapArrow+  {-# INLINE _Wrapped' #-}++instance (t ~ ZipList b) => Rewrapped (ZipList a) t+instance Wrapped (ZipList a) where+  type Unwrapped (ZipList a) = [a]+  _Wrapped' = iso getZipList ZipList+  {-# INLINE _Wrapped' #-}++instance (t ~ NonEmpty b) => Rewrapped (NonEmpty a) t+instance Wrapped (NonEmpty a) where+  type Unwrapped (NonEmpty a) = (a, [a])+  _Wrapped' = iso (\(a :| as) -> (a, as)) (\(a,as) -> a :| as)+  {-# INLINE _Wrapped' #-}++instance (t ~ Const a' x') => Rewrapped (Const a x) t+instance Wrapped (Const a x) where+  type Unwrapped (Const a x) = a+  _Wrapped' = iso getConst Const+  {-# INLINE _Wrapped' #-}++instance (t ~ Dual b) => Rewrapped (Dual a) t+instance Wrapped (Dual a) where+  type Unwrapped (Dual a) = a+  _Wrapped' = iso getDual Dual+  {-# INLINE _Wrapped' #-}++instance (t ~ Endo b) => Rewrapped (Endo a) t+instance Wrapped (Endo a) where+  type Unwrapped (Endo a) = a -> a+  _Wrapped' = iso appEndo Endo+  {-# INLINE _Wrapped' #-}++instance (t ~ First b) => Rewrapped (First a) t+instance Wrapped (First a) where+  type Unwrapped (First a) = Maybe a+  _Wrapped' = iso getFirst First+  {-# INLINE _Wrapped' #-}++instance (t ~ Last b) => Rewrapped (Last a) t+instance Wrapped (Last a) where+  type Unwrapped (Last a) = Maybe a+  _Wrapped' = iso getLast Last+  {-# INLINE _Wrapped' #-}++instance (t ~ Monoid.Alt g b) => Rewrapped (Monoid.Alt f a) t+instance Wrapped (Monoid.Alt f a) where+  type Unwrapped (Monoid.Alt f a) = f a+  _Wrapped' = iso Monoid.getAlt Monoid.Alt+  {-# INLINE _Wrapped' #-}++#if MIN_VERSION_base(4,12,0)+instance (t ~ Monoid.Ap g b) => Rewrapped (Monoid.Ap f a) t+instance Wrapped (Monoid.Ap f a) where+  type Unwrapped (Monoid.Ap f a) = f a+  _Wrapped' = iso Monoid.getAp Monoid.Ap+  {-# INLINE _Wrapped' #-}+#endif++instance t ~ ArrowMonad m' a' => Rewrapped (ArrowMonad m a) t+instance Wrapped (ArrowMonad m a) where+  type Unwrapped (ArrowMonad m a) = m () a+  _Wrapped' = iso getArrowMonad ArrowMonad+  {-# INLINE _Wrapped' #-}++instance t ~ Down b => Rewrapped (Down a) t+instance Wrapped (Down a) where+  type Unwrapped (Down a) = a+  _Wrapped' = iso (\(Down a) -> a) Down+  {-# INLINE _Wrapped' #-}++instance Rewrapped Errno t+instance Wrapped Errno where+  type Unwrapped Errno = CInt+  _Wrapped' = iso (\(Errno x) -> x) Errno+  {-# INLINE _Wrapped' #-}++getArrowMonad :: ArrowMonad m a -> m () a+getArrowMonad (ArrowMonad x) = x+{-# INLINE getArrowMonad #-}++-- * transformers++instance (t ~ Backwards g b) => Rewrapped (Backwards f a) t+instance Wrapped (Backwards f a) where+  type Unwrapped (Backwards f a) = f a+  _Wrapped' = iso forwards Backwards++instance (t ~ Compose f' g' a') => Rewrapped (Compose f g a) t+instance Wrapped (Compose f g a) where+  type Unwrapped (Compose f g a) = f (g a)+  _Wrapped' = iso getCompose Compose++instance (t ~ Constant a' b') => Rewrapped (Constant a b) t+instance Wrapped (Constant a b) where+  type Unwrapped (Constant a b) = a+  _Wrapped' = iso getConstant Constant++instance (t ~ ContT r' m' a') => Rewrapped (ContT r m a) t+instance Wrapped (ContT r m a) where+  type Unwrapped (ContT r m a) = (a -> m r) -> m r+  _Wrapped' = iso runContT ContT++instance (t ~ ExceptT e' m' a') => Rewrapped (ExceptT e m a) t+instance Wrapped (ExceptT e m a) where+  type Unwrapped (ExceptT e m a) = m (Either e a)+  _Wrapped' = iso runExceptT ExceptT+  {-# INLINE _Wrapped' #-}++instance (t ~ Identity b) => Rewrapped (Identity a) t+instance Wrapped (Identity a) where+  type Unwrapped (Identity a) = a+  _Wrapped' = iso runIdentity Identity+  {-# INLINE _Wrapped' #-}++instance (t ~ IdentityT n b) => Rewrapped (IdentityT m a) t+instance Wrapped (IdentityT m a) where+  type Unwrapped (IdentityT m a) = m a+  _Wrapped' = iso runIdentityT IdentityT+  {-# INLINE _Wrapped' #-}++instance (t ~ MaybeT n b) => Rewrapped (MaybeT m a) t+instance Wrapped (MaybeT m a) where+  type Unwrapped (MaybeT m a) = m (Maybe a)+  _Wrapped' = iso runMaybeT MaybeT+  {-# INLINE _Wrapped' #-}++instance (t ~ ReaderT s n b) => Rewrapped (ReaderT r m a) t+instance Wrapped (ReaderT r m a) where+  type Unwrapped (ReaderT r m a) = r -> m a+  _Wrapped' = iso runReaderT ReaderT+  {-# INLINE _Wrapped' #-}++instance (t ~ Reverse g b) => Rewrapped (Reverse f a) t+instance Wrapped (Reverse f a) where+  type Unwrapped (Reverse f a) = f a+  _Wrapped' = iso getReverse Reverse+  {-# INLINE _Wrapped' #-}++instance (t ~ Lazy.RWST r' w' s' m' a') => Rewrapped (Lazy.RWST r w s m a) t+instance Wrapped (Lazy.RWST r w s m a) where+  type Unwrapped (Lazy.RWST r w s m a) = r -> s -> m (a, s, w)+  _Wrapped' = iso Lazy.runRWST Lazy.RWST+  {-# INLINE _Wrapped' #-}++instance (t ~ Strict.RWST r' w' s' m' a') => Rewrapped (Strict.RWST r w s m a) t+instance Wrapped (Strict.RWST r w s m a) where+  type Unwrapped (Strict.RWST r w s m a) = r -> s -> m (a, s, w)+  _Wrapped' = iso Strict.runRWST Strict.RWST+  {-# INLINE _Wrapped' #-}++instance (t ~ Lazy.StateT s' m' a') => Rewrapped (Lazy.StateT s m a) t+instance Wrapped (Lazy.StateT s m a) where+  type Unwrapped (Lazy.StateT s m a) = s -> m (a, s)+  _Wrapped' = iso Lazy.runStateT Lazy.StateT+  {-# INLINE _Wrapped' #-}++instance (t ~ Strict.StateT s' m' a') => Rewrapped (Strict.StateT s m a) t+instance Wrapped (Strict.StateT s m a) where+  type Unwrapped (Strict.StateT s m a) = s -> m (a, s)+  _Wrapped' = iso Strict.runStateT Strict.StateT+  {-# INLINE _Wrapped' #-}++instance (t ~ Lazy.WriterT w' m' a') => Rewrapped (Lazy.WriterT w m a) t+instance Wrapped (Lazy.WriterT w m a) where+  type Unwrapped (Lazy.WriterT w m a) = m (a, w)+  _Wrapped' = iso Lazy.runWriterT Lazy.WriterT+  {-# INLINE _Wrapped' #-}++instance (t ~ Strict.WriterT w' m' a') => Rewrapped (Strict.WriterT w m a) t+instance Wrapped (Strict.WriterT w m a) where+  type Unwrapped (Strict.WriterT w m a) = m (a, w)+  _Wrapped' = iso Strict.runWriterT Strict.WriterT+  {-# INLINE _Wrapped' #-}++#if !MIN_VERSION_transformers(0,6,0)+instance (t ~ ErrorT e' m' a') => Rewrapped (ErrorT e m a) t+instance Wrapped (ErrorT e m a) where+  type Unwrapped (ErrorT e m a) = m (Either e a)+  _Wrapped' = iso runErrorT ErrorT+  {-# INLINE _Wrapped' #-}++instance (t ~ ListT n b) => Rewrapped (ListT m a) t+instance Wrapped (ListT m a) where+  type Unwrapped (ListT m a) = m [a]+  _Wrapped' = iso runListT ListT+  {-# INLINE _Wrapped' #-}+#endif++-- * bifunctors++instance (t ~ Biff p' f' g' a' b') => Rewrapped (Biff p f g a b) t+instance Wrapped (Biff p f g a b) where+  type Unwrapped (Biff p f g a b) = p (f a) (g b)+  _Wrapped' = iso runBiff Biff+  {-# INLINE _Wrapped' #-}++instance (t ~ Clown f' a' b') => Rewrapped (Clown f a b) t+instance Wrapped (Clown f a b) where+  type Unwrapped (Clown f a b) = f a+  _Wrapped' = iso runClown Clown+  {-# INLINE _Wrapped' #-}++instance (t ~ Fix p' a') => Rewrapped (Fix p a) t+instance Wrapped (Fix p a) where+  type Unwrapped (Fix p a) = p (Fix p a) a+  _Wrapped' = iso out In+  {-# INLINE _Wrapped' #-}++instance (t ~ Flip p' a' b') => Rewrapped (Flip p a b) t+instance Wrapped (Flip p a b) where+  type Unwrapped (Flip p a b) = p b a+  _Wrapped' = iso runFlip Flip+  {-# INLINE _Wrapped' #-}++instance (t ~ Join p' a') => Rewrapped (Join p a) t+instance Wrapped (Join p a) where+  type Unwrapped (Join p a) = p a a+  _Wrapped' = iso runJoin Join+  {-# INLINE _Wrapped' #-}++instance (t ~ Joker g' a' b') => Rewrapped (Joker g a b) t+instance Wrapped (Joker g a b) where+  type Unwrapped (Joker g a b) = g b+  _Wrapped' = iso runJoker Joker+  {-# INLINE _Wrapped' #-}++instance (t ~ Tannen f' p' a' b') => Rewrapped (Tannen f p a b) t+instance Wrapped (Tannen f p a b) where+  type Unwrapped (Tannen f p a b) = f (p a b)+  _Wrapped' = iso runTannen Tannen+  {-# INLINE _Wrapped' #-}++instance (t ~ WrappedBifunctor p' a' b') => Rewrapped (WrappedBifunctor p a b) t+instance Wrapped (WrappedBifunctor p a b) where+  type Unwrapped (WrappedBifunctor p a b) = p a b+  _Wrapped' = iso unwrapBifunctor WrapBifunctor+  {-# INLINE _Wrapped' #-}++-- * comonad++instance (t ~ TracedT m' w' a') => Rewrapped (TracedT m w a) t+instance Wrapped (TracedT m w a) where+  type Unwrapped (TracedT m w a) = w (m -> a)+  _Wrapped' = iso runTracedT TracedT+  {-# INLINE _Wrapped' #-}++-- * exceptions++instance (t ~ CatchT m' a') => Rewrapped (CatchT m a) t+instance Wrapped (CatchT m a) where+  type Unwrapped (CatchT m a) = m (Either SomeException a)+  _Wrapped' = iso runCatchT CatchT+  {-# INLINE _Wrapped' #-}++-- * free++instance (t ~ Free.Alt f' a') => Rewrapped (Free.Alt f a) t+instance Wrapped (Free.Alt f a) where+  type Unwrapped (Free.Alt f a) = [Free.AltF f a]+  _Wrapped' = iso Free.alternatives Free.Alt+  {-# INLINE _Wrapped' #-}++instance (t ~ ApT f' g' a') => Rewrapped (ApT f g a) t+instance Wrapped (ApT f g a) where+  type Unwrapped (ApT f g a) = g (ApF f g a)+  _Wrapped' = iso getApT ApT+  {-# INLINE _Wrapped' #-}++instance (t ~ CofreeT f' w' a') => Rewrapped (CofreeT f w a) t+instance Wrapped (CofreeT f w a) where+  type Unwrapped (CofreeT f w a) = w (CofreeF f a (CofreeT f w a))+  _Wrapped' = iso runCofreeT CofreeT+  {-# INLINE _Wrapped' #-}++instance (t ~ CoiterT w' a') => Rewrapped (CoiterT w a) t+instance Wrapped (CoiterT w a) where+  type Unwrapped (CoiterT w a) = w (a, CoiterT w a)+  _Wrapped' = iso runCoiterT CoiterT+  {-# INLINE _Wrapped' #-}++instance (t ~ FreeT f' m' a') => Rewrapped (FreeT f m a) t+instance Wrapped (FreeT f m a) where+  type Unwrapped (FreeT f m a) = m (FreeF f a (FreeT f m a))+  _Wrapped' = iso runFreeT FreeT+  {-# INLINE _Wrapped' #-}++instance (t ~ IterT m' a') => Rewrapped (IterT m a) t+instance Wrapped (IterT m a) where+  type Unwrapped (IterT m a) = m (Either a (IterT m a))+  _Wrapped' = iso runIterT IterT+  {-# INLINE _Wrapped' #-}++-- * unordered-containers++-- | Use @'_Wrapping' 'HashMap.fromList'@. Unwrapping returns some permutation of the list.+instance (t ~ HashMap k' a', Hashable k, Eq k) => Rewrapped (HashMap k a) t+instance (Hashable k, Eq k) => Wrapped (HashMap k a) where+  type Unwrapped (HashMap k a) = [(k, a)]+  _Wrapped' = iso HashMap.toList HashMap.fromList+  {-# INLINE _Wrapped' #-}++-- | Use @'_Wrapping' 'HashSet.fromList'@. Unwrapping returns some permutation of the list.+instance (t ~ HashSet a', Hashable a, Eq a) => Rewrapped (HashSet a) t+instance (Hashable a, Eq a) => Wrapped (HashSet a) where+  type Unwrapped (HashSet a) = [a]+  _Wrapped' = iso HashSet.toList HashSet.fromList+  {-# INLINE _Wrapped' #-}++-- * containers++-- | Use @'_Wrapping' 'IntMap.fromList'@. unwrapping returns a /sorted/ list.+instance (t ~ IntMap a') => Rewrapped (IntMap a) t+instance Wrapped (IntMap a) where+  type Unwrapped (IntMap a) = [(Int, a)]+  _Wrapped' = iso IntMap.toAscList IntMap.fromList+  {-# INLINE _Wrapped' #-}++-- | Use @'_Wrapping' 'IntSet.fromList'@. unwrapping returns a /sorted/ list.+instance (t ~ IntSet) => Rewrapped IntSet t+instance Wrapped IntSet where+  type Unwrapped IntSet = [Int]+  _Wrapped' = iso IntSet.toAscList IntSet.fromList+  {-# INLINE _Wrapped' #-}++-- | Use @'_Wrapping' 'Map.fromList'@. unwrapping returns a /sorted/ list.+instance (t ~ Map k' a', Ord k) => Rewrapped (Map k a) t+instance Ord k => Wrapped (Map k a) where+  type Unwrapped (Map k a) = [(k, a)]+  _Wrapped' = iso Map.toAscList Map.fromList+  {-# INLINE _Wrapped' #-}++-- | Use @'_Wrapping' 'Set.fromList'@. unwrapping returns a /sorted/ list.+instance (t ~ Set a', Ord a) => Rewrapped (Set a) t+instance Ord a => Wrapped (Set a) where+  type Unwrapped (Set a) = [a]+  _Wrapped' = iso Set.toAscList Set.fromList+  {-# INLINE _Wrapped' #-}++instance (t ~ Seq a') => Rewrapped (Seq a) t+instance Wrapped (Seq a) where+  type Unwrapped (Seq a) = [a]+  _Wrapped' = iso Foldable.toList Seq.fromList+  {-# INLINE _Wrapped' #-}++-- * profunctors++instance (t ~ Star f' d' c') => Rewrapped (Star f d c) t+instance Wrapped (Star f d c) where+  type Unwrapped (Star f d c) = d -> f c+  _Wrapped' = iso runStar Star+  {-# INLINE _Wrapped' #-}++instance (t ~ Costar f' d' c') => Rewrapped (Costar f d c) t+instance Wrapped (Costar f d c) where+  type Unwrapped (Costar f d c) = f d -> c+  _Wrapped' = iso runCostar Costar+  {-# INLINE _Wrapped' #-}++instance (t ~ Profunctor.WrappedArrow p' a' b') => Rewrapped (Profunctor.WrappedArrow p a b) t+instance Wrapped (Profunctor.WrappedArrow p a b) where+  type Unwrapped (Profunctor.WrappedArrow p a b) = p a b+  _Wrapped' = iso Profunctor.unwrapArrow Profunctor.WrapArrow+  {-# INLINE _Wrapped' #-}++instance (t ~ Forget r' a' b') => Rewrapped (Forget r a b) t+instance Wrapped (Forget r a b) where+  type Unwrapped (Forget r a b) = a -> r+  _Wrapped' = iso runForget Forget+  {-# INLINE _Wrapped' #-}++instance (t ~ Cayley f' p' a' b') => Rewrapped (Cayley f p a b) t+instance Wrapped (Cayley f p a b) where+  type Unwrapped (Cayley f p a b) = f (p a b)+  _Wrapped' = iso runCayley Cayley+  {-# INLINE _Wrapped' #-}++-- * vector++instance (t ~ Vector.Vector a') => Rewrapped (Vector.Vector a) t+instance Wrapped (Vector.Vector a) where+  type Unwrapped (Vector.Vector a) = [a]+  _Wrapped' = iso Vector.toList Vector.fromList+  {-# INLINE _Wrapped' #-}++instance (Prim a, t ~ Prim.Vector a') => Rewrapped (Prim.Vector a) t+instance Prim a => Wrapped (Prim.Vector a) where+  type Unwrapped (Prim.Vector a) = [a]+  _Wrapped' = iso Prim.toList Prim.fromList+  {-# INLINE _Wrapped' #-}++instance (Unbox a, t ~ Unboxed.Vector a') => Rewrapped (Unboxed.Vector a) t+instance Unbox a => Wrapped (Unboxed.Vector a) where+  type Unwrapped (Unboxed.Vector a) = [a]+  _Wrapped' = iso Unboxed.toList Unboxed.fromList+  {-# INLINE _Wrapped' #-}++instance (Storable a, t ~ Storable.Vector a') => Rewrapped (Storable.Vector a) t+instance Storable a => Wrapped (Storable.Vector a) where+  type Unwrapped (Storable.Vector a) = [a]+  _Wrapped' = iso Storable.toList Storable.fromList+  {-# INLINE _Wrapped' #-}++#if MIN_VERSION_vector(0,13,2)+instance (t ~ Vector.Vector a') => Rewrapped (VectorStrict.Vector a) t+instance Wrapped (VectorStrict.Vector a) where+  type Unwrapped (VectorStrict.Vector a) = [a]+  _Wrapped' = iso VectorStrict.toList VectorStrict.fromList+  {-# INLINE _Wrapped' #-}+#endif++-- * semigroupoids++instance (t ~ WrappedApplicative f' a') => Rewrapped (WrappedApplicative f a) t+instance Wrapped (WrappedApplicative f a) where+  type Unwrapped (WrappedApplicative f a) = f a+  _Wrapped' = iso unwrapApplicative WrapApplicative+  {-# INLINE _Wrapped' #-}++instance (t ~ MaybeApply f' a') => Rewrapped (MaybeApply f a) t+instance Wrapped (MaybeApply f a) where+  type Unwrapped (MaybeApply f a) = Either (f a) a+  _Wrapped' = iso runMaybeApply MaybeApply+  {-# INLINE _Wrapped' #-}++instance (t ~ WrappedCategory k' a' b') => Rewrapped (WrappedCategory k a b) t+instance Wrapped (WrappedCategory k a b) where+  type Unwrapped (WrappedCategory k a b) = k a b+  _Wrapped' = iso unwrapCategory WrapCategory+  {-# INLINE _Wrapped' #-}++instance (t ~ Semi m' a' b') => Rewrapped (Semi m a b) t+instance Wrapped (Semi m a b) where+  type Unwrapped (Semi m a b) = m+  _Wrapped' = iso getSemi Semi+  {-# INLINE _Wrapped' #-}++instance (t ~ Semigroupoid.Dual k' a' b') => Rewrapped (Semigroupoid.Dual k a b) t+instance Wrapped (Semigroupoid.Dual k a b) where+  type Unwrapped (Semigroupoid.Dual k a b) = k b a+  _Wrapped' = iso Semigroupoid.getDual Semigroupoid.Dual+  {-# INLINE _Wrapped' #-}++instance (t ~ Static f' a' b') => Rewrapped (Static f a b) t+instance Wrapped (Static f a b) where+  type Unwrapped (Static f a b) = f (a -> b)+  _Wrapped' = iso runStatic Static+  {-# INLINE _Wrapped' #-}++-- * semigroups++instance (t ~ S.Min b) => Rewrapped (S.Min a) t+instance Wrapped (S.Min a) where+  type Unwrapped (S.Min a) = a+  _Wrapped' = iso S.getMin S.Min+  {-# INLINE _Wrapped' #-}++instance (t ~ S.Max b) => Rewrapped (S.Max a) t+instance Wrapped (S.Max a) where+  type Unwrapped (S.Max a) = a+  _Wrapped' = iso S.getMax S.Max+  {-# INLINE _Wrapped' #-}++instance (t ~ S.First b) => Rewrapped (S.First a) t+instance Wrapped (S.First a) where+  type Unwrapped (S.First a) = a+  _Wrapped' = iso S.getFirst S.First+  {-# INLINE _Wrapped' #-}++instance (t ~ S.Last b) => Rewrapped (S.Last a) t+instance Wrapped (S.Last a) where+  type Unwrapped (S.Last a) = a+  _Wrapped' = iso S.getLast S.Last+  {-# INLINE _Wrapped' #-}++instance (t ~ S.WrappedMonoid b) => Rewrapped (S.WrappedMonoid a) t+instance Wrapped (S.WrappedMonoid a) where+  type Unwrapped (S.WrappedMonoid a) = a+  _Wrapped' = iso S.unwrapMonoid S.WrapMonoid+  {-# INLINE _Wrapped' #-}++#if !(MIN_VERSION_base(4,16,0))+instance (t ~ S.Option b) => Rewrapped (S.Option a) t+instance Wrapped (S.Option a) where+  type Unwrapped (S.Option a) = Maybe a+  _Wrapped' = iso S.getOption S.Option+  {-# INLINE _Wrapped' #-}+#endif++-- * contravariant++instance (t ~ Predicate b) => Rewrapped (Predicate a) t+instance Wrapped (Predicate a) where+  type Unwrapped (Predicate a) = a -> Bool+  _Wrapped' = iso getPredicate Predicate+  {-# INLINE _Wrapped' #-}++instance (t ~ Comparison b) => Rewrapped (Comparison a) t+instance Wrapped (Comparison a) where+  type Unwrapped (Comparison a) = a -> a -> Ordering+  _Wrapped' = iso getComparison Comparison+  {-# INLINE _Wrapped' #-}++instance (t ~ Equivalence b) => Rewrapped (Equivalence a) t+instance Wrapped (Equivalence a) where+  type Unwrapped (Equivalence a) = a -> a -> Bool+  _Wrapped' = iso getEquivalence Equivalence+  {-# INLINE _Wrapped' #-}++instance (t ~ Op a' b') => Rewrapped (Op a b) t+instance Wrapped (Op a b) where+  type Unwrapped (Op a b) = b -> a+  _Wrapped' = iso getOp Op+  {-# INLINE _Wrapped' #-}++instance (t ~ Contravariant.Compose f' g' a') => Rewrapped (Contravariant.Compose f g a) t+instance Wrapped (Contravariant.Compose f g a) where+  type Unwrapped (Contravariant.Compose f g a) = f (g a)+  _Wrapped' = iso Contravariant.getCompose Contravariant.Compose+  {-# INLINE _Wrapped' #-}++instance (t ~ Contravariant.ComposeFC f' g' a') => Rewrapped (Contravariant.ComposeFC f g a) t+instance Wrapped (Contravariant.ComposeFC f g a) where+  type Unwrapped (Contravariant.ComposeFC f g a) = f (g a)+  _Wrapped' = iso Contravariant.getComposeFC Contravariant.ComposeFC+  {-# INLINE _Wrapped' #-}++instance (t ~ Contravariant.ComposeCF f' g' a') => Rewrapped (Contravariant.ComposeCF f g a) t+instance Wrapped (Contravariant.ComposeCF f g a) where+  type Unwrapped (Contravariant.ComposeCF f g a) = f (g a)+  _Wrapped' = iso Contravariant.getComposeCF Contravariant.ComposeCF+  {-# INLINE _Wrapped' #-}++-- * tagged++instance (t ~ Tagged s' a') => Rewrapped (Tagged s a) t+instance Wrapped (Tagged s a) where+  type Unwrapped (Tagged s a) = a+  _Wrapped' = iso unTagged Tagged+  {-# INLINE _Wrapped' #-}++-- * Control.Exception++instance (t ~ AssertionFailed) => Rewrapped AssertionFailed t+instance Wrapped AssertionFailed where+  type Unwrapped AssertionFailed = String+  _Wrapped' = iso failedAssertion AssertionFailed+  {-# INLINE _Wrapped' #-}++instance (t ~ NoMethodError) => Rewrapped NoMethodError t+instance Wrapped NoMethodError where+  type Unwrapped NoMethodError = String+  _Wrapped' = iso getNoMethodError NoMethodError+  {-# INLINE _Wrapped' #-}++instance (t ~ PatternMatchFail) => Rewrapped PatternMatchFail t+instance Wrapped PatternMatchFail where+  type Unwrapped PatternMatchFail = String+  _Wrapped' = iso getPatternMatchFail PatternMatchFail+  {-# INLINE _Wrapped' #-}++instance (t ~ RecConError) => Rewrapped RecConError t+instance Wrapped RecConError where+  type Unwrapped RecConError = String+  _Wrapped' = iso getRecConError RecConError+  {-# INLINE _Wrapped' #-}++instance (t ~ RecSelError) => Rewrapped RecSelError t+instance Wrapped RecSelError where+  type Unwrapped RecSelError = String+  _Wrapped' = iso getRecSelError RecSelError+  {-# INLINE _Wrapped' #-}++instance (t ~ RecUpdError) => Rewrapped RecUpdError t+instance Wrapped RecUpdError where+  type Unwrapped RecUpdError = String+  _Wrapped' = iso getRecUpdError RecUpdError+  {-# INLINE _Wrapped' #-}++instance (t ~ ErrorCall) => Rewrapped ErrorCall t+instance Wrapped ErrorCall where+  type Unwrapped ErrorCall = String+  _Wrapped' = iso getErrorCall ErrorCall+  {-# INLINE _Wrapped' #-}++instance (t ~ TypeError) => Rewrapped TypeError t+instance Wrapped TypeError where+  type Unwrapped TypeError = String+  _Wrapped' = iso getTypeError TypeError+  {-# INLINE _Wrapped' #-}++getTypeError :: TypeError -> String+getTypeError (TypeError x) = x+{-# INLINE getTypeError #-}++#if MIN_VERSION_base(4,10,0)+instance (t ~ CompactionFailed) => Rewrapped CompactionFailed t+instance Wrapped CompactionFailed where+  type Unwrapped CompactionFailed = String+  _Wrapped' = iso getCompactionFailed CompactionFailed+  {-# INLINE _Wrapped' #-}++getCompactionFailed :: CompactionFailed -> String+getCompactionFailed (CompactionFailed x) = x+{-# INLINE getCompactionFailed #-}+#endif++getErrorCall :: ErrorCall -> String+#if MIN_VERSION_base(4,21,0)+getErrorCall (ErrorCall x) = x+#else+getErrorCall (ErrorCallWithLocation x _) = x+#endif+{-# INLINE getErrorCall #-}++getRecUpdError :: RecUpdError -> String+getRecUpdError (RecUpdError x) = x+{-# INLINE getRecUpdError #-}++getRecSelError :: RecSelError -> String+getRecSelError (RecSelError x) = x+{-# INLINE getRecSelError #-}++getRecConError :: RecConError -> String+getRecConError (RecConError x) = x+{-# INLINE getRecConError #-}++getPatternMatchFail :: PatternMatchFail -> String+getPatternMatchFail (PatternMatchFail x) = x+{-# INLINE getPatternMatchFail #-}++getNoMethodError :: NoMethodError -> String+getNoMethodError (NoMethodError x) = x+{-# INLINE getNoMethodError #-}++failedAssertion :: AssertionFailed -> String+failedAssertion (AssertionFailed x) = x+{-# INLINE failedAssertion #-}++-- * Foreign.C.Types++instance Rewrapped CChar t+instance Wrapped CChar where+  type Unwrapped CChar = HTYPE_CHAR+  _Wrapped' = iso (\(CChar x) -> x) CChar+  {-# INLINE _Wrapped' #-}++instance Rewrapped CSChar t+instance Wrapped CSChar where+  type Unwrapped CSChar = HTYPE_SIGNED_CHAR+  _Wrapped' = iso (\(CSChar x) -> x) CSChar+  {-# INLINE _Wrapped' #-}++instance Rewrapped CUChar t+instance Wrapped CUChar where+  type Unwrapped CUChar = HTYPE_UNSIGNED_CHAR+  _Wrapped' = iso (\(CUChar x) -> x) CUChar+  {-# INLINE _Wrapped' #-}++instance Rewrapped CShort t+instance Wrapped CShort where+  type Unwrapped CShort = HTYPE_SHORT+  _Wrapped' = iso (\(CShort x) -> x) CShort+  {-# INLINE _Wrapped' #-}++instance Rewrapped CUShort t+instance Wrapped CUShort where+  type Unwrapped CUShort = HTYPE_UNSIGNED_SHORT+  _Wrapped' = iso (\(CUShort x) -> x) CUShort+  {-# INLINE _Wrapped' #-}++instance Rewrapped CInt t+instance Wrapped CInt where+  type Unwrapped CInt = HTYPE_INT+  _Wrapped' = iso (\(CInt x) -> x) CInt+  {-# INLINE _Wrapped' #-}++instance Rewrapped CUInt t+instance Wrapped CUInt where+  type Unwrapped CUInt = HTYPE_UNSIGNED_INT+  _Wrapped' = iso (\(CUInt x) -> x) CUInt+  {-# INLINE _Wrapped' #-}++instance Rewrapped CLong t+instance Wrapped CLong where+  type Unwrapped CLong = HTYPE_LONG+  _Wrapped' = iso (\(CLong x) -> x) CLong+  {-# INLINE _Wrapped' #-}++instance Rewrapped CULong t+instance Wrapped CULong where+  type Unwrapped CULong = HTYPE_UNSIGNED_LONG+  _Wrapped' = iso (\(CULong x) -> x) CULong+  {-# INLINE _Wrapped' #-}++instance Rewrapped CLLong t+instance Wrapped CLLong where+  type Unwrapped CLLong = HTYPE_LONG_LONG+  _Wrapped' = iso (\(CLLong x) -> x) CLLong+  {-# INLINE _Wrapped' #-}++instance Rewrapped CULLong t+instance Wrapped CULLong where+  type Unwrapped CULLong = HTYPE_UNSIGNED_LONG_LONG+  _Wrapped' = iso (\(CULLong x) -> x) CULLong+  {-# INLINE _Wrapped' #-}++instance Rewrapped CFloat t+instance Wrapped CFloat where+  type Unwrapped CFloat = HTYPE_FLOAT+  _Wrapped' = iso (\(CFloat x) -> x) CFloat+  {-# INLINE _Wrapped' #-}++instance Rewrapped CDouble t+instance Wrapped CDouble where+  type Unwrapped CDouble = HTYPE_DOUBLE+  _Wrapped' = iso (\(CDouble x) -> x) CDouble+  {-# INLINE _Wrapped' #-}++instance Rewrapped CPtrdiff t+instance Wrapped CPtrdiff where+  type Unwrapped CPtrdiff = HTYPE_PTRDIFF_T+  _Wrapped' = iso (\(CPtrdiff x) -> x) CPtrdiff+  {-# INLINE _Wrapped' #-}++instance Rewrapped CSize t+instance Wrapped CSize where+  type Unwrapped CSize = HTYPE_SIZE_T+  _Wrapped' = iso (\(CSize x) -> x) CSize+  {-# INLINE _Wrapped' #-}++instance Rewrapped CWchar t+instance Wrapped CWchar where+  type Unwrapped CWchar = HTYPE_WCHAR_T+  _Wrapped' = iso (\(CWchar x) -> x) CWchar+  {-# INLINE _Wrapped' #-}++instance Rewrapped CSigAtomic t+instance Wrapped CSigAtomic where+  type Unwrapped CSigAtomic =+#if defined(HTYPE_SIG_ATOMIC_T)+    HTYPE_SIG_ATOMIC_T+#else+    Int32+#endif+  _Wrapped' = iso (\(CSigAtomic x) -> x) CSigAtomic+  {-# INLINE _Wrapped' #-}++instance Rewrapped CClock t+instance Wrapped CClock where+  type Unwrapped CClock = HTYPE_CLOCK_T+  _Wrapped' = iso (\(CClock x) -> x) CClock+  {-# INLINE _Wrapped' #-}++instance Rewrapped CTime t+instance Wrapped CTime where+  type Unwrapped CTime = HTYPE_TIME_T+  _Wrapped' = iso (\(CTime x) -> x) CTime+  {-# INLINE _Wrapped' #-}++instance Rewrapped CUSeconds t+instance Wrapped CUSeconds where+  type Unwrapped CUSeconds = HTYPE_USECONDS_T+  _Wrapped' = iso (\(CUSeconds x) -> x) CUSeconds+  {-# INLINE _Wrapped' #-}++instance Rewrapped CSUSeconds t+instance Wrapped CSUSeconds where+  type Unwrapped CSUSeconds = HTYPE_SUSECONDS_T+  _Wrapped' = iso (\(CSUSeconds x) -> x) CSUSeconds+  {-# INLINE _Wrapped' #-}++instance Rewrapped CIntPtr t+instance Wrapped CIntPtr where+  type Unwrapped CIntPtr = HTYPE_INTPTR_T+  _Wrapped' = iso (\(CIntPtr x) -> x) CIntPtr+  {-# INLINE _Wrapped' #-}++instance Rewrapped CUIntPtr t+instance Wrapped CUIntPtr where+  type Unwrapped CUIntPtr = HTYPE_UINTPTR_T+  _Wrapped' = iso (\(CUIntPtr x) -> x) CUIntPtr+  {-# INLINE _Wrapped' #-}++instance Rewrapped CIntMax t+instance Wrapped CIntMax where+  type Unwrapped CIntMax = HTYPE_INTMAX_T+  _Wrapped' = iso (\(CIntMax x) -> x) CIntMax+  {-# INLINE _Wrapped' #-}++instance Rewrapped CUIntMax t+instance Wrapped CUIntMax where+  type Unwrapped CUIntMax = HTYPE_UINTMAX_T+  _Wrapped' = iso (\(CUIntMax x) -> x) CUIntMax+  {-# INLINE _Wrapped' #-}++-- * GHC.Generics++instance (t ~ Par1 p') => Rewrapped (Par1 p) t+instance Wrapped (Par1 p) where+  type Unwrapped (Par1 p) = p+  _Wrapped' = iso unPar1 Par1+  {-# INLINE _Wrapped' #-}++instance (t ~ Rec1 f' p') => Rewrapped (Rec1 f p) t+instance Wrapped (Rec1 f p) where+  type Unwrapped (Rec1 f p) = f p+  _Wrapped' = iso unRec1 Rec1+  {-# INLINE _Wrapped' #-}++instance (t ~ K1 i' c' p') => Rewrapped (K1 i c p) t+instance Wrapped (K1 i c p) where+  type Unwrapped (K1 i c p) = c+  _Wrapped' = iso unK1 K1+  {-# INLINE _Wrapped' #-}++instance (t ~ M1 i' c' f' p') => Rewrapped (M1 i c f p) t+instance Wrapped (M1 i c f p) where+  type Unwrapped (M1 i c f p) = f p+  _Wrapped' = iso unM1 M1+  {-# INLINE _Wrapped' #-}++instance (t ~ (f' :.: g') p') => Rewrapped ((f :.: g) p) t+instance Wrapped ((f :.: g) p) where+  type Unwrapped ((f :.: g) p) = f (g p)+  _Wrapped' = iso unComp1 Comp1+  {-# INLINE _Wrapped' #-}++-- * System.Posix.Types++#if defined(HTYPE_DEV_T)+instance Rewrapped CDev t+instance Wrapped CDev where+  type Unwrapped CDev = HTYPE_DEV_T+  _Wrapped' = iso (\(CDev x) -> x) CDev+  {-# INLINE _Wrapped' #-}+#endif++#if defined(HTYPE_INO_T)+instance Rewrapped CIno t+instance Wrapped CIno where+  type Unwrapped CIno = HTYPE_INO_T+  _Wrapped' = iso (\(CIno x) -> x) CIno+  {-# INLINE _Wrapped' #-}+#endif++#if defined(HTYPE_MODE_T)+instance Rewrapped CMode t+instance Wrapped CMode where+  type Unwrapped CMode = HTYPE_MODE_T+  _Wrapped' = iso (\(CMode x) -> x) CMode+  {-# INLINE _Wrapped' #-}+#endif++#if defined(HTYPE_OFF_T)+instance Rewrapped COff t+instance Wrapped COff where+  type Unwrapped COff = HTYPE_OFF_T+  _Wrapped' = iso (\(COff x) -> x) COff+  {-# INLINE _Wrapped' #-}+#endif++#if defined(HTYPE_PID_T)+instance Rewrapped CPid t+instance Wrapped CPid where+  type Unwrapped CPid = HTYPE_PID_T+  _Wrapped' = iso (\(CPid x) -> x) CPid+  {-# INLINE _Wrapped' #-}+#endif++#if defined(HTYPE_SSIZE_T)+instance Rewrapped CSsize t+instance Wrapped CSsize where+  type Unwrapped CSsize = HTYPE_SSIZE_T+  _Wrapped' = iso (\(CSsize x) -> x) CSsize+  {-# INLINE _Wrapped' #-}+#endif++#if defined(HTYPE_GID_T)+instance Rewrapped CGid t+instance Wrapped CGid where+  type Unwrapped CGid = HTYPE_GID_T+  _Wrapped' = iso (\(CGid x) -> x) CGid+  {-# INLINE _Wrapped' #-}+#endif++#if defined(HTYPE_NLINK_T)+instance Rewrapped CNlink t+instance Wrapped CNlink where+  type Unwrapped CNlink = HTYPE_NLINK_T+  _Wrapped' = iso (\(CNlink x) -> x) CNlink+  {-# INLINE _Wrapped' #-}+#endif++#if defined(HTYPE_UID_T)+instance Rewrapped CUid t+instance Wrapped CUid where+  type Unwrapped CUid = HTYPE_UID_T+  _Wrapped' = iso (\(CUid x) -> x) CUid+  {-# INLINE _Wrapped' #-}+#endif++#if defined(HTYPE_CC_T)+instance Rewrapped CCc t+instance Wrapped CCc where+  type Unwrapped CCc = HTYPE_CC_T+  _Wrapped' = iso (\(CCc x) -> x) CCc+  {-# INLINE _Wrapped' #-}+#endif++#if defined(HTYPE_SPEED_T)+instance Rewrapped CSpeed t+instance Wrapped CSpeed where+  type Unwrapped CSpeed = HTYPE_SPEED_T+  _Wrapped' = iso (\(CSpeed x) -> x) CSpeed+  {-# INLINE _Wrapped' #-}+#endif++#if defined(HTYPE_TCFLAG_T)+instance Rewrapped CTcflag t+instance Wrapped CTcflag where+  type Unwrapped CTcflag = HTYPE_TCFLAG_T+  _Wrapped' = iso (\(CTcflag x) -> x) CTcflag+  {-# INLINE _Wrapped' #-}+#endif++#if defined(HTYPE_RLIM_T)+instance Rewrapped CRLim t+instance Wrapped CRLim where+  type Unwrapped CRLim = HTYPE_RLIM_T+  _Wrapped' = iso (\(CRLim x) -> x) CRLim+  {-# INLINE _Wrapped' #-}+#endif++instance Rewrapped Fd t+instance Wrapped Fd where+  type Unwrapped Fd = CInt+  _Wrapped' = iso (\(Fd x) -> x) Fd+  {-# INLINE _Wrapped' #-}++#if MIN_VERSION_base(4,10,0)+instance Rewrapped CBool t+instance Wrapped CBool where+  type Unwrapped CBool = HTYPE_BOOL+  _Wrapped' = iso (\(CBool x) -> x) CBool+  {-# INLINE _Wrapped' #-}++# if defined(HTYPE_BLKSIZE_T)+instance Rewrapped CBlkSize t+instance Wrapped CBlkSize where+  type Unwrapped CBlkSize = HTYPE_BLKSIZE_T+  _Wrapped' = iso (\(CBlkSize x) -> x) CBlkSize+  {-# INLINE _Wrapped' #-}+# endif++# if defined(HTYPE_BLKCNT_T)+instance Rewrapped CBlkCnt t+instance Wrapped CBlkCnt where+  type Unwrapped CBlkCnt = HTYPE_BLKCNT_T+  _Wrapped' = iso (\(CBlkCnt x) -> x) CBlkCnt+  {-# INLINE _Wrapped' #-}+# endif++# if defined(HTYPE_CLOCKID_T)+instance Rewrapped CClockId t+instance Wrapped CClockId where+  type Unwrapped CClockId = HTYPE_CLOCKID_T+  _Wrapped' = iso (\(CClockId x) -> x) CClockId+  {-# INLINE _Wrapped' #-}+# endif++# if defined(HTYPE_FSBLKCNT_T)+instance Rewrapped CFsBlkCnt t+instance Wrapped CFsBlkCnt where+  type Unwrapped CFsBlkCnt = HTYPE_FSBLKCNT_T+  _Wrapped' = iso (\(CFsBlkCnt x) -> x) CFsBlkCnt+  {-# INLINE _Wrapped' #-}+# endif++# if defined(HTYPE_FSFILCNT_T)+instance Rewrapped CFsFilCnt t+instance Wrapped CFsFilCnt where+  type Unwrapped CFsFilCnt = HTYPE_FSFILCNT_T+  _Wrapped' = iso (\(CFsFilCnt x) -> x) CFsFilCnt+  {-# INLINE _Wrapped' #-}+# endif++# if defined(HTYPE_ID_T)+instance Rewrapped CId t+instance Wrapped CId where+  type Unwrapped CId = HTYPE_ID_T+  _Wrapped' = iso (\(CId x) -> x) CId+  {-# INLINE _Wrapped' #-}+# endif++# if defined(HTYPE_KEY_T)+instance Rewrapped CKey t+instance Wrapped CKey where+  type Unwrapped CKey = HTYPE_KEY_T+  _Wrapped' = iso (\(CKey x) -> x) CKey+  {-# INLINE _Wrapped' #-}+# endif++# if defined(HTYPE_TIMER_T)+instance Rewrapped CTimer t+instance Wrapped CTimer where+  type Unwrapped CTimer = HTYPE_TIMER_T+  _Wrapped' = iso (\(CTimer x) -> x) CTimer+  {-# INLINE _Wrapped' #-}+# endif+#endif++-- | Given the constructor for a t'Wrapped' type, return a+-- deconstructor that is its inverse.+--+-- Assuming the t'Wrapped' instance is legal, these laws hold:+--+-- @+-- 'op' f '.' f ≡ 'id'+-- f '.' 'op' f ≡ 'id'+-- @+--+--+-- >>> op Identity (Identity 4)+-- 4+--+-- >>> op Const (Const "hello")+-- "hello"+op :: Wrapped s => (Unwrapped s -> s) -> s -> Unwrapped s+op _ = view _Wrapped'+{-# INLINE op #-}++-- | This is a convenient version of '_Wrapped' with an argument that's ignored.+--+-- The user supplied function is /ignored/, merely its type is used.+_Wrapping' :: Wrapped s => (Unwrapped s -> s) -> Iso' s (Unwrapped s)+_Wrapping' _ = _Wrapped'+{-# INLINE _Wrapping' #-}++-- | This is a convenient version of '_Wrapped' with an argument that's ignored.+--+-- The user supplied function is /ignored/, merely its type is used.+_Unwrapping' :: Wrapped s => (Unwrapped s -> s) -> Iso' (Unwrapped s) s+_Unwrapping' _ = from _Wrapped'+{-# INLINE _Unwrapping' #-}++-- | This is a convenient version of '_Wrapped' with an argument that's ignored.+--+-- The user supplied function is /ignored/, merely its types are used.+_Wrapping :: Rewrapping s t => (Unwrapped s -> s) -> Iso s t (Unwrapped s) (Unwrapped t)+_Wrapping _ = _Wrapped+{-# INLINE _Wrapping #-}++-- | This is a convenient version of '_Unwrapped' with an argument that's ignored.+--+-- The user supplied function is /ignored/, merely its types are used.+_Unwrapping :: Rewrapping s t => (Unwrapped s -> s) -> Iso (Unwrapped t) (Unwrapped s) t s+_Unwrapping _ = from _Wrapped+{-# INLINE _Unwrapping #-}++-- | This combinator is based on @ala@ from Conor McBride's work on Epigram.+--+-- As with '_Wrapping', the user supplied function for the newtype is /ignored/.+--+-- >>> ala Sum foldMap [1,2,3,4]+-- 10+--+-- >>> ala All foldMap [True,True]+-- True+--+-- >>> ala All foldMap [True,False]+-- False+--+-- >>> ala Any foldMap [False,False]+-- False+--+-- >>> ala Any foldMap [True,False]+-- True+--+-- >>> ala Product foldMap [1,2,3,4]+-- 24+--+--+-- You may want to think of this combinator as having the following, simpler, type.+--+-- @+-- ala :: Rewrapping s t => (Unwrapped s -> s) -> ((Unwrapped t -> t) -> e -> s) -> e -> Unwrapped s+-- @++ala :: (Functor f, Rewrapping s t) => (Unwrapped s -> s) -> ((Unwrapped t -> t) -> f s) -> f (Unwrapped s)+ala f = xplat $ _Unwrapping f+{-# INLINE ala #-}++-- | This combinator is based on @ala'@ from Conor McBride's work on Epigram.+--+-- As with '_Wrapping', the user supplied function for the newtype is /ignored/.+--+-- @+-- alaf :: Rewrapping s t => (Unwrapped s -> s) -> ((r -> t) -> e -> s) -> (r -> Unwrapped t) -> e -> Unwrapped s+-- @+--+-- >>> alaf Sum foldMap Prelude.length ["hello","world"]+-- 10+alaf :: (Functor f, Functor g, Rewrapping s t) => (Unwrapped s -> s) -> (f t -> g s) -> f (Unwrapped t) -> g (Unwrapped s)+alaf f = xplatf $ _Unwrapping f+{-# INLINE alaf #-}
src/Control/Lens/Zoom.hs view
@@ -1,15 +1,23 @@ {-# LANGUAGE CPP #-}-{-# LANGUAGE Rank2Types #-}-{-# LANGUAGE LiberalTypeSynonyms #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE Trustworthy #-} +#if !MIN_VERSION_transformers(0,6,0)+{-# OPTIONS_GHC -Wno-warnings-deprecations #-}+#endif++#include "lens-common.h"+ ------------------------------------------------------------------------------- -- | -- Module      :  Control.Lens.Zoom--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional@@ -17,141 +25,267 @@ -- ------------------------------------------------------------------------------- module Control.Lens.Zoom-  ( Magnify(..)+  ( Magnified+  , Magnify(..)   , Zoom(..)+  , Zoomed   ) where -import Control.Lens.Internal-import Control.Lens.Type+import Prelude ()+ import Control.Lens.Getter+import Control.Lens.Internal.Prelude+import Control.Lens.Internal.Zoom+import Control.Lens.Type import Control.Monad-import Control.Monad.Reader.Class       as Reader-import Control.Monad.State.Class        as State-import Control.Monad.Trans.State.Lazy   as Lazy+import Control.Monad.Reader as Reader+import Control.Monad.State as State+import Control.Monad.Trans.State.Lazy as Lazy import Control.Monad.Trans.State.Strict as Strict-import Control.Monad.Trans.Writer.Lazy   as Lazy+import Control.Monad.Trans.Writer.Lazy as Lazy import Control.Monad.Trans.Writer.Strict as Strict-import Control.Monad.Trans.RWS.Lazy   as Lazy+import Control.Monad.Trans.RWS.Lazy as Lazy import Control.Monad.Trans.RWS.Strict as Strict-import Control.Monad.Trans.Reader-import Control.Monad.Trans.Error-import Control.Monad.Trans.List+#if MIN_VERSION_mtl(2,3,0)+import Control.Monad.Trans.RWS.CPS as CPS+#endif+import Control.Monad.Trans.Except import Control.Monad.Trans.Identity import Control.Monad.Trans.Maybe-import Data.Monoid+import Control.Monad.Trans.Free+#if !MIN_VERSION_transformers(0,6,0)+import Control.Monad.Trans.Error+import Control.Monad.Trans.List+#endif+import Data.Kind --- | This class allows us to use 'zoom' in, changing the State supplied by--- many different monad transformers, potentially quite deep in a monad transformer stack.-class (MonadState s m, MonadState t n) => Zoom m n k s t | m -> s k, n -> t k, m t -> n, n s -> m where-  -- | Run a monadic action in a larger state than it was defined in,-  -- using a 'Simple' 'Lens' or 'Simple' 'Control.Lens.Traversal.Traversal'.+-- $setup+-- >>> import Control.Lens+-- >>> import Control.Monad.State as State+-- >>> import Control.Monad.Reader as Reader+-- >>> import qualified Data.Map as Map+-- >>> import Debug.SimpleReflect.Expr as Expr+-- >>> import Debug.SimpleReflect.Vars as Vars+-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f+-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g+-- >>> let h :: Expr -> Expr -> Expr; h = Debug.SimpleReflect.Vars.h++-- Chosen so that they have lower fixity than ('%='), and to match ('<~').+infixr 2 `zoom`, `magnify`++------------------------------------------------------------------------------+-- Zoomed+------------------------------------------------------------------------------++-- | This type family is used by 'Control.Lens.Zoom.Zoom' to describe the common effect type.+type family Zoomed (m :: Type -> Type) :: Type -> Type -> Type+type instance Zoomed (Strict.StateT s z) = Focusing z+type instance Zoomed (Lazy.StateT s z) = Focusing z+type instance Zoomed (ReaderT e m) = Zoomed m+type instance Zoomed (IdentityT m) = Zoomed m+type instance Zoomed (Strict.RWST r w s z) = FocusingWith w z+type instance Zoomed (Lazy.RWST r w s z) = FocusingWith w z+type instance Zoomed (Strict.WriterT w m) = FocusingPlus w (Zoomed m)+type instance Zoomed (Lazy.WriterT w m) = FocusingPlus w (Zoomed m)+type instance Zoomed (MaybeT m) = FocusingMay (Zoomed m)+type instance Zoomed (ExceptT e m) = FocusingErr e (Zoomed m)+type instance Zoomed (FreeT f m) = FocusingFree f m (Zoomed m)+#if !MIN_VERSION_transformers(0,6,0)+type instance Zoomed (ErrorT e m) = FocusingErr e (Zoomed m)+type instance Zoomed (ListT m) = FocusingOn [] (Zoomed m)+#endif++------------------------------------------------------------------------------+-- Magnified+------------------------------------------------------------------------------++-- | This type family is used by 'Control.Lens.Zoom.Magnify' to describe the common effect type.+type family Magnified (m :: Type -> Type) :: Type -> Type -> Type+type instance Magnified (ReaderT b m) = Effect m+type instance Magnified ((->)b) = Const+type instance Magnified (Strict.RWST a w s m) = EffectRWS w s m+type instance Magnified (Lazy.RWST a w s m) = EffectRWS w s m+#if MIN_VERSION_mtl(2,3,0)+type instance Magnified (CPS.RWST a w s m) = EffectRWS w s m+#endif+type instance Magnified (IdentityT m) = Magnified m++------------------------------------------------------------------------------+-- Zoom+------------------------------------------------------------------------------++-- | This class allows us to use 'zoom' in, changing the 'State' supplied by+-- many different 'Control.Monad.Monad' transformers, potentially quite+-- deep in a 'Monad' transformer stack.+class (MonadState s m, MonadState t n) => Zoom m n s t | m -> s, n -> t, m t -> n, n s -> m where+  -- | Run a monadic action in a larger 'State' than it was defined in,+  -- using a 'Lens'' or 'Control.Lens.Traversal.Traversal''.   ---  -- This is commonly used to lift actions in a simpler state monad into a-  -- state monad with a larger state type.+  -- This is commonly used to lift actions in a simpler 'State'+  -- 'Monad' into a 'State' 'Monad' with a larger 'State' type.   ---  -- When applied to a 'Simple 'Control.Lens.Traversal.Traversal' over+  -- When applied to a 'Control.Lens.Traversal.Traversal'' over   -- multiple values, the actions for each target are executed sequentially   -- and the results are aggregated.   ---  -- This can be used to edit pretty much any monad transformer stack with a state in it!+  -- This can be used to edit pretty much any 'Monad' transformer stack with a 'State' in it!   --+  -- >>> flip State.evalState (a,b) $ zoom _1 $ use id+  -- a+  --+  -- >>> flip State.execState (a,b) $ zoom _1 $ id .= c+  -- (c,b)+  --+  -- >>> flip State.execState [(a,b),(c,d)] $ zoom traverse $ _2 %= f+  -- [(a,f b),(c,f d)]+  --+  -- >>> flip State.runState [(a,b),(c,d)] $ zoom traverse $ _2 <%= f+  -- (f b <> f d <> mempty,[(a,f b),(c,f d)])+  --+  -- >>> flip State.evalState (a,b) $ zoom both (use id)+  -- a <> b+  --   -- @-  -- 'zoom' :: 'Monad' m             => 'Simple' 'Lens' a b      -> 'StateT' b m c -> 'StateT' a m c-  -- 'zoom' :: ('Monad' m, 'Monoid' c) => 'Simple' 'Control.Lens.Traversal.Traversal' a b -> 'StateT' b m c -> 'StateT' a m c-  -- 'zoom' :: 'Monad' m             => 'Simple' 'Lens' a b      -> 'RWST' r w b m c -> 'RWST' r w a m c-  -- 'zoom' :: ('Monad' m, 'Monoid' c) => 'Simple' 'Control.Lens.Traversal.Traversal' a b -> 'RWST' r w b m c -> 'RWST' r w a m c-  -- 'zoom' :: 'Monad' m             => 'Simple' 'Lens' a b      -> 'ErrorT' e ('RWST' r w b m c) -> 'ErrorT' e ('RWST' r w a m c)-  -- 'zoom' :: ('Monad' m, 'Monoid' c) => 'Simple' 'Control.Lens.Traversal.Traversal' a b -> 'ErrorT' e ('RWST' r w b m c) -> 'ErrorT' e ('RWST' r w a m c)+  -- 'zoom' :: 'Monad' m             => 'Lens'' s t      -> 'StateT' t m a -> 'StateT' s m a+  -- 'zoom' :: ('Monad' m, 'Monoid' c) => 'Control.Lens.Traversal.Traversal'' s t -> 'StateT' t m c -> 'StateT' s m c+  -- 'zoom' :: ('Monad' m, 'Monoid' w)             => 'Lens'' s t      -> 'RWST' r w t m c -> 'RWST' r w s m c+  -- 'zoom' :: ('Monad' m, 'Monoid' w, 'Monoid' c) => 'Control.Lens.Traversal.Traversal'' s t -> 'RWST' r w t m c -> 'RWST' r w s m c+  -- 'zoom' :: ('Monad' m, 'Monoid' w, 'Error' e)  => 'Lens'' s t      -> 'ErrorT' e ('RWST' r w t m) c -> 'ErrorT' e ('RWST' r w s m) c+  -- 'zoom' :: ('Monad' m, 'Monoid' w, 'Monoid' c, 'Error' e) => 'Control.Lens.Traversal.Traversal'' s t -> 'ErrorT' e ('RWST' r w t m) c -> 'ErrorT' e ('RWST' r w s m) c   -- ...   -- @-  zoom :: Monad m => SimpleLensLike (k c) t s -> m c -> n c+  zoom :: LensLike' (Zoomed m c) t s -> m c -> n c -instance Monad z => Zoom (Strict.StateT s z) (Strict.StateT t z) (Focusing z) s t where-  zoom l (Strict.StateT m) = Strict.StateT $ unfocusing . l (Focusing . m)+instance Monad z => Zoom (Strict.StateT s z) (Strict.StateT t z) s t where+  zoom l (Strict.StateT m) = Strict.StateT $ unfocusing #. l (Focusing #. m)   {-# INLINE zoom #-} -instance Monad z => Zoom (Lazy.StateT s z) (Lazy.StateT t z) (Focusing z) s t where-  zoom l (Lazy.StateT m) = Lazy.StateT $ unfocusing . l (Focusing . m)+instance Monad z => Zoom (Lazy.StateT s z) (Lazy.StateT t z) s t where+  zoom l (Lazy.StateT m) = Lazy.StateT $ unfocusing #. l (Focusing #. m)   {-# INLINE zoom #-} -instance Zoom m n k s t => Zoom (ReaderT e m) (ReaderT e n) k s t where+instance Zoom m n s t => Zoom (ReaderT e m) (ReaderT e n) s t where   zoom l (ReaderT m) = ReaderT (zoom l . m)   {-# INLINE zoom #-} -instance Zoom m n k s t => Zoom (IdentityT m) (IdentityT n) k s t where+instance Zoom m n s t => Zoom (IdentityT m) (IdentityT n) s t where   zoom l (IdentityT m) = IdentityT (zoom l m)   {-# INLINE zoom #-} -instance (Monoid w, Monad z) => Zoom (Strict.RWST r w s z) (Strict.RWST r w t z) (FocusingWith w z) s t where-  zoom l (Strict.RWST m) = Strict.RWST $ \r -> unfocusingWith . l (FocusingWith . m r)+instance (Monoid w, Monad z) => Zoom (Strict.RWST r w s z) (Strict.RWST r w t z) s t where+  zoom l (Strict.RWST m) = Strict.RWST $ \r -> unfocusingWith #. l (FocusingWith #. m r)   {-# INLINE zoom #-} -instance (Monoid w, Monad z) => Zoom (Lazy.RWST r w s z) (Lazy.RWST r w t z) (FocusingWith w z) s t where-  zoom l (Lazy.RWST m) = Lazy.RWST $ \r -> unfocusingWith . l (FocusingWith . m r)+instance (Monoid w, Monad z) => Zoom (Lazy.RWST r w s z) (Lazy.RWST r w t z) s t where+  zoom l (Lazy.RWST m) = Lazy.RWST $ \r -> unfocusingWith #. l (FocusingWith #. m r)   {-# INLINE zoom #-} -instance (Monoid w, Zoom m n k s t) => Zoom (Strict.WriterT w m) (Strict.WriterT w n) (FocusingPlus w k) s t where-  zoom l = Strict.WriterT . zoom (\cfd -> unfocusingPlus . l (FocusingPlus  . cfd)) . Strict.runWriterT+instance (Monoid w, Zoom m n s t) => Zoom (Strict.WriterT w m) (Strict.WriterT w n) s t where+  zoom l = Strict.WriterT . zoom (\afb -> unfocusingPlus #. l (FocusingPlus #. afb)) . Strict.runWriterT   {-# INLINE zoom #-} -instance (Monoid w, Zoom m n k s t) => Zoom (Lazy.WriterT w m) (Lazy.WriterT w n) (FocusingPlus w k) s t where-  zoom l = Lazy.WriterT . zoom (\cfd -> unfocusingPlus . l (FocusingPlus  . cfd)) . Lazy.runWriterT+instance (Monoid w, Zoom m n s t) => Zoom (Lazy.WriterT w m) (Lazy.WriterT w n) s t where+  zoom l = Lazy.WriterT . zoom (\afb -> unfocusingPlus #. l (FocusingPlus #. afb)) . Lazy.runWriterT   {-# INLINE zoom #-} -instance Zoom m n k s t => Zoom (ListT m) (ListT n) (FocusingOn [] k) s t where-  zoom l = ListT . zoom (\cfd -> unfocusingOn . l (FocusingOn . cfd)) . runListT+instance Zoom m n s t => Zoom (MaybeT m) (MaybeT n) s t where+  zoom l = MaybeT . liftM getMay . zoom (\afb -> unfocusingMay #. l (FocusingMay #. afb)) . liftM May . runMaybeT   {-# INLINE zoom #-} -instance Zoom m n k s t => Zoom (MaybeT m) (MaybeT n) (FocusingMay k) s t where-  zoom l = MaybeT . liftM getMay . zoom (\cfd -> unfocusingMay . l (FocusingMay . cfd)) . liftM May . runMaybeT+instance Zoom m n s t => Zoom (ExceptT e m) (ExceptT e n) s t where+  zoom l = ExceptT . liftM getErr . zoom (\afb -> unfocusingErr #. l (FocusingErr #. afb)) . liftM Err . runExceptT   {-# INLINE zoom #-} -instance (Error e, Zoom m n k s t) => Zoom (ErrorT e m) (ErrorT e n) (FocusingErr e k) s t where-  zoom l = ErrorT . liftM getErr . zoom (\cfd -> unfocusingErr . l (FocusingErr . cfd)) . liftM Err . runErrorT+instance (Functor f, Zoom m n s t) => Zoom (FreeT f m) (FreeT f n) s t where+  zoom l = FreeT . liftM (fmap (zoom l) . getFreed) . zoom (\afb -> unfocusingFree #. l (FocusingFree #. afb)) . liftM Freed . runFreeT++#if !MIN_VERSION_transformers(0,6,0) && !MIN_VERSION_mtl(2,3,0)+instance (Error e, Zoom m n s t) => Zoom (ErrorT e m) (ErrorT e n) s t where+  zoom l = ErrorT . liftM getErr . zoom (\afb -> unfocusingErr #. l (FocusingErr #. afb)) . liftM Err . runErrorT   {-# INLINE zoom #-} --- TODO: instance Zoom m m k a a => Zoom (ContT r m) (ContT r m) k a a where+instance Zoom m n s t => Zoom (ListT m) (ListT n) s t where+  zoom l = ListT . zoom (\afb -> unfocusingOn . l (FocusingOn . afb)) . runListT+  {-# INLINE zoom #-}+#endif +------------------------------------------------------------------------------+-- Magnify+------------------------------------------------------------------------------ +-- TODO: instance Zoom m m a a => Zoom (ContT r m) (ContT r m) a a where+ -- | This class allows us to use 'magnify' part of the environment, changing the environment supplied by--- many different monad transformers. Unlike 'focus' this can change the environment of a deeply nested monad transformer.+-- many different 'Monad' transformers. Unlike 'zoom' this can change the environment of a deeply nested 'Monad' transformer. ----- Also, unlike 'focus', this can be used with any valid 'Getter', but cannot be used with a 'Traversal' or 'Fold'.-class (MonadReader b m, MonadReader a n) => Magnify m n k b a | m -> b, n -> a, m a -> n, n b -> m where+-- Also, unlike 'zoom', this can be used with any valid 'Getter', but cannot be used with a 'Traversal' or 'Fold'.+class (Magnified m ~ Magnified n, MonadReader b m, MonadReader a n) => Magnify m n b a | m -> b, n -> a, m a -> n, n b -> m where   -- | Run a monadic action in a larger environment than it was defined in, using a 'Getter'.   --   -- This acts like 'Control.Monad.Reader.Class.local', but can in many cases change the type of the environment as well.   ---  -- This is commonly used to lift actions in a simpler Reader monad into a monad with a larger environment type.+  -- This is commonly used to lift actions in a simpler 'Reader' 'Monad' into a 'Monad' with a larger environment type.   ---  -- This can be used to edit pretty much any monad transformer stack with an environment in it:+  -- This can be used to edit pretty much any 'Monad' transformer stack with an environment in it:   --+  -- >>> (1,2) & magnify _2 (+1)+  -- 3+  --+  -- >>> flip Reader.runReader (1,2) $ magnify _1 Reader.ask+  -- 1+  --+  -- >>> flip Reader.runReader (1,2,[10..20]) $ magnify (_3._tail) Reader.ask+  -- [11,12,13,14,15,16,17,18,19,20]+  --+  -- The type can be read as+  --   -- @-  -- 'magnify' ::             'Getter' a b -> (b -> c) -> a -> c-  -- 'magnify' :: 'Monoid' c => 'Fold' a b   -> (b -> c) -> a -> c-  -- 'magnify' :: 'Monoid' w                'Getter' a b -> 'RWST' a w s c -> 'RWST' b w s c-  -- 'magnify' :: ('Monoid' w, 'Monoid' c) => 'Fold' a b   -> 'RWST' a w s c -> 'RWST' b w s c+  --   magnify :: LensLike' (Magnified m c) a b -> m c -> n c+  -- @+  --+  -- but the higher-rank constraints make it easier to apply @magnify@ to a+  -- 'Getter' in highly-polymorphic code.+  --+  -- @+  -- 'magnify' :: 'Getter' s a -> (a -> r) -> s -> r+  -- 'magnify' :: 'Monoid' r => 'Fold' s a   -> (a -> r) -> s -> r+  -- @+  --+  -- @+  -- 'magnify' :: 'Monoid' w                 => 'Getter' s t -> 'RWS' t w st c -> 'RWS' s w st c+  -- 'magnify' :: ('Monoid' w, 'Monoid' c) => 'Fold' s a   -> 'RWS' a w st c -> 'RWS' s w st c   -- ...   -- @-  magnify :: ((b -> k c b) -> a -> k c a) -> m c -> n c+  magnify :: ((Functor (Magnified m c), Contravariant (Magnified m c))+                => LensLike' (Magnified m c) a b)+          -> m c -> n c -instance Monad m => Magnify (ReaderT b m) (ReaderT a m) (Effect m) b a where-  magnify l (ReaderT m) = ReaderT $ getEffect . l (Effect . m)++instance Monad m => Magnify (ReaderT b m) (ReaderT a m) b a where+  magnify l (ReaderT m) = ReaderT $ getEffect #. l (Effect #. m)   {-# INLINE magnify #-} --- | @'magnify' = 'views'@-instance Magnify ((->) b) ((->) a) Accessor b a where-  magnify = views+-- | @+-- 'magnify' = 'views'+-- @+instance Magnify ((->) b) ((->) a) b a where+  magnify l = views l   {-# INLINE magnify #-} -instance (Monad m, Monoid w) => Magnify (Strict.RWST b w s m) (Strict.RWST a w s m) (EffectRWS w s m) b a where-  magnify l (Strict.RWST m) = Strict.RWST $ getEffectRWS . l (EffectRWS . m)+instance (Monad m, Monoid w) => Magnify (Strict.RWST b w s m) (Strict.RWST a w s m) b a where+  magnify l (Strict.RWST m) = Strict.RWST $ getEffectRWS #. l (EffectRWS #. m)   {-# INLINE magnify #-} -instance (Monad m, Monoid w) => Magnify (Lazy.RWST b w s m) (Lazy.RWST a w s m) (EffectRWS w s m) b a where-  magnify l (Lazy.RWST m) = Lazy.RWST $ getEffectRWS . l (EffectRWS . m)+instance (Monad m, Monoid w) => Magnify (Lazy.RWST b w s m) (Lazy.RWST a w s m) b a where+  magnify l (Lazy.RWST m) = Lazy.RWST $ getEffectRWS #. l (EffectRWS #. m)   {-# INLINE magnify #-} -instance Magnify m n k b a => Magnify (IdentityT m) (IdentityT n) k b a where+#if MIN_VERSION_mtl(2,3,0)+instance (Monad m, Monoid w, MonadReader b (CPS.RWST b w s m)) => Magnify (CPS.RWST b w s m) (CPS.RWST a w s m) b a where+  magnify l m = CPS.rwsT $ getEffectRWS #. l (EffectRWS #. CPS.runRWST m)+  {-# INLINE magnify #-}+#endif++instance Magnify m n b a => Magnify (IdentityT m) (IdentityT n) b a where   magnify l (IdentityT m) = IdentityT (magnify l m)   {-# INLINE magnify #-}
+ src/Control/Monad/Error/Lens.hs view
@@ -0,0 +1,242 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE ExistentialQuantification #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE FlexibleInstances #-}+-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Monad.Error.Lens+-- Copyright   :  (C) 2014-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  Control.Monad.Error+--+----------------------------------------------------------------------------+module Control.Monad.Error.Lens+  (+  -- * Catching+    catching, catching_+  -- * Handling+  , handling, handling_+  -- * Trying+  , trying+  -- * Handlers+  , catches+  , Handler(..)+  , Handleable(..)+  -- * Throwing+  , throwing, throwing_+  ) where++import Control.Applicative+import Control.Lens+import Control.Lens.Internal.Exception+import Control.Monad+import Control.Monad.Error.Class+import Data.Functor.Plus+import qualified Data.Monoid as M++#if !(MIN_VERSION_base(4,11,0))+import Data.Semigroup (Semigroup(..))+#endif++------------------------------------------------------------------------------+-- Catching+------------------------------------------------------------------------------++-- | Catch exceptions that match a given t'Prism' (or any t'Getter', really).+--+-- @+-- 'catching' :: 'MonadError' e m => 'Prism'' e a     -> m r -> (a -> m r) -> m r+-- 'catching' :: 'MonadError' e m => 'Lens'' e a      -> m r -> (a -> m r) -> m r+-- 'catching' :: 'MonadError' e m => 'Traversal'' e a -> m r -> (a -> m r) -> m r+-- 'catching' :: 'MonadError' e m => 'Iso'' e a       -> m r -> (a -> m r) -> m r+-- 'catching' :: 'MonadError' e m => t'Getter' e a    -> m r -> (a -> m r) -> m r+-- 'catching' :: 'MonadError' e m => t'Fold' e a      -> m r -> (a -> m r) -> m r+-- @+catching :: MonadError e m => Getting (M.First a) e a -> m r -> (a -> m r) -> m r+catching l = catchJust (preview l)+{-# INLINE catching #-}++-- | Catch exceptions that match a given t'Prism' (or any t'Getter'), discarding+-- the information about the match. This is particularly useful when you have+-- a @'Prism'' e ()@ where the result of the t'Prism' or t'Fold' isn't+-- particularly valuable, just the fact that it matches.+--+-- @+-- 'catching_' :: 'MonadError' e m => 'Prism'' e a     -> m r -> m r -> m r+-- 'catching_' :: 'MonadError' e m => 'Lens'' e a      -> m r -> m r -> m r+-- 'catching_' :: 'MonadError' e m => 'Traversal'' e a -> m r -> m r -> m r+-- 'catching_' :: 'MonadError' e m => 'Iso'' e a       -> m r -> m r -> m r+-- 'catching_' :: 'MonadError' e m => t'Getter' e a    -> m r -> m r -> m r+-- 'catching_' :: 'MonadError' e m => t'Fold' e a      -> m r -> m r -> m r+-- @+catching_ :: MonadError e m => Getting (M.First a) e a -> m r -> m r -> m r+catching_ l a b = catchJust (preview l) a (const b)+{-# INLINE catching_ #-}++------------------------------------------------------------------------------+-- Handling+------------------------------------------------------------------------------++-- | A version of 'catching' with the arguments swapped around; useful in+-- situations where the code for the handler is shorter.+--+-- @+-- 'handling' :: 'MonadError' e m => 'Prism'' e a     -> (a -> m r) -> m r -> m r+-- 'handling' :: 'MonadError' e m => 'Lens'' e a      -> (a -> m r) -> m r -> m r+-- 'handling' :: 'MonadError' e m => 'Traversal'' e a -> (a -> m r) -> m r -> m r+-- 'handling' :: 'MonadError' e m => 'Iso'' e a       -> (a -> m r) -> m r -> m r+-- 'handling' :: 'MonadError' e m => t'Fold' e a      -> (a -> m r) -> m r -> m r+-- 'handling' :: 'MonadError' e m => t'Getter' e a    -> (a -> m r) -> m r -> m r+-- @+handling :: MonadError e m => Getting (M.First a) e a -> (a -> m r) -> m r -> m r+handling l = flip (catching l)+{-# INLINE handling #-}++-- | A version of 'catching_' with the arguments swapped around; useful in+-- situations where the code for the handler is shorter.+--+-- @+-- 'handling_' :: 'MonadError' e m => 'Prism'' e a     -> m r -> m r -> m r+-- 'handling_' :: 'MonadError' e m => 'Lens'' e a      -> m r -> m r -> m r+-- 'handling_' :: 'MonadError' e m => 'Traversal'' e a -> m r -> m r -> m r+-- 'handling_' :: 'MonadError' e m => 'Iso'' e a       -> m r -> m r -> m r+-- 'handling_' :: 'MonadError' e m => t'Getter' e a    -> m r -> m r -> m r+-- 'handling_' :: 'MonadError' e m => t'Fold' e a      -> m r -> m r -> m r+-- @+handling_ :: MonadError e m => Getting (M.First a) e a -> m r -> m r -> m r+handling_ l = flip (catching_ l)+{-# INLINE handling_ #-}++------------------------------------------------------------------------------+-- Trying+------------------------------------------------------------------------------++-- | 'trying' takes a t'Prism' (or any t'Getter') to select which exceptions are caught+-- If the exception does not match the predicate, it is re-thrown.+--+-- @+-- 'trying' :: 'MonadError' e m => 'Prism'' e a     -> m r -> m ('Either' a r)+-- 'trying' :: 'MonadError' e m => 'Lens'' e a      -> m r -> m ('Either' a r)+-- 'trying' :: 'MonadError' e m => 'Traversal'' e a -> m r -> m ('Either' a r)+-- 'trying' :: 'MonadError' e m => 'Iso'' e a       -> m r -> m ('Either' a r)+-- 'trying' :: 'MonadError' e m => t'Getter' e a    -> m r -> m ('Either' a r)+-- 'trying' :: 'MonadError' e m => t'Fold' e a      -> m r -> m ('Either' a r)+-- @+trying :: MonadError e m => Getting (M.First a) e a -> m r -> m (Either a r)+trying l m = catching l (liftM Right m) (return . Left)++------------------------------------------------------------------------------+-- Catches+------------------------------------------------------------------------------++-- |+-- This function exists to remedy a gap between the functionality of @Control.Exception@+-- and @Control.Monad.Error@. @Control.Exception@ supplies 'Control.Exception.catches' and+-- a notion of 'Control.Exception.Handler', which we duplicate here in a form suitable for+-- working with any 'MonadError' instance.+--+-- Sometimes you want to catch two different sorts of error. You could+-- do something like+--+-- @+-- f = 'handling' _Foo handleFoo ('handling' _Bar handleBar expr)+-- @+--+--+-- However, there are a couple of problems with this approach. The first is+-- that having two exception handlers is inefficient. However, the more+-- serious issue is that the second exception handler will catch exceptions+-- in the first, e.g. in the example above, if @handleFoo@ uses 'throwError'+-- then the second exception handler will catch it.+--+-- Instead, we provide a function 'catches', which would be used thus:+--+-- @+-- f = 'catches' expr [ 'handler' _Foo handleFoo+--                  , 'handler' _Bar handleBar+--                  ]+-- @+catches :: MonadError e m => m a -> [Handler e m a] -> m a+catches m hs = catchError m go where+  go e = foldr tryHandler (throwError e) hs where+    tryHandler (Handler ema amr) res = maybe res amr (ema e)++------------------------------------------------------------------------------+-- Handlers+------------------------------------------------------------------------------++-- | You need this when using 'catches'.+data Handler e m r = forall a. Handler (e -> Maybe a) (a -> m r)++instance Monad m => Functor (Handler e m) where+  fmap f (Handler ema amr) = Handler ema $ \a -> do+     r <- amr a+     return (f r)+  {-# INLINE fmap #-}++instance Monad m => Semigroup (Handler e m a) where+  (<>) = (<!>)+  {-# INLINE (<>) #-}++instance Monad m => Alt (Handler e m) where+  Handler ema amr <!> Handler emb bmr = Handler emab abmr where+    emab e = Left <$> ema e <|> Right <$> emb e+    abmr = either amr bmr+  {-# INLINE (<!>) #-}++instance Monad m => Plus (Handler e m) where+  zero = Handler (const Nothing) undefined+  {-# INLINE zero #-}++instance Monad m => M.Monoid (Handler e m a) where+  mempty = zero+  {-# INLINE mempty #-}+#if !(MIN_VERSION_base(4,11,0))+  mappend = (<!>)+  {-# INLINE mappend #-}+#endif++instance Handleable e m (Handler e m) where+  handler = Handler . preview+  {-# INLINE handler #-}++------------------------------------------------------------------------------+-- Throwing+------------------------------------------------------------------------------++-- | Throw an exception described by a t'Prism'.+--+-- @'throwing' l ≡ 'reviews' l 'throwError'@+--+-- @+-- 'throwing' :: 'MonadError' e m => 'Prism'' e t -> t -> m a+-- 'throwing' :: 'MonadError' e m => 'Iso'' e t   -> t -> m a+-- @+throwing :: MonadError e m => AReview e t -> t -> m x+throwing l = reviews l throwError+{-# INLINE throwing #-}++------------------------------------------------------------------------------+-- Misc.+------------------------------------------------------------------------------++-- | Helper function to provide conditional catch behavior.+catchJust :: MonadError e m => (e -> Maybe t) -> m a -> (t -> m a) -> m a+catchJust f m k = catchError m $ \ e -> case f e of+  Nothing -> throwError e+  Just x  -> k x+{-# INLINE catchJust #-}++-- | Similar to 'throwing' but specialised for the common case of+--   error constructors with no arguments.+--+-- @+-- data MyError = Foo | Bar+-- makePrisms ''MyError+-- 'throwing_' _Foo :: 'MonadError' MyError m => m a+-- @+throwing_ :: MonadError e m => AReview e () -> m x+throwing_ l = throwing l ()+{-# INLINE throwing_ #-}
src/Control/Parallel/Strategies/Lens.hs view
@@ -1,13 +1,20 @@+{-# LANGUAGE CPP #-}+#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-}+#endif++#include "lens-common.h"+ ----------------------------------------------------------------------------- -- | -- Module      :  Control.Parallel.Strategies.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-2016 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional -- Portability :  portable ----- A 'Lens' or 'Traversal' can be used to take the role of 'Traversable' in+-- A t'Lens' or t'Traversal' can be used to take the role of 'Traversable' in -- @Control.Parallel.Strategies@, enabling those combinators to work with -- monomorphic containers. ----------------------------------------------------------------------------@@ -21,7 +28,7 @@ import Control.Lens import Control.Parallel.Strategies --- | Evaluate the targets of a 'Lens' or 'Traversal' into a data structure+-- | Evaluate the targets of a t'Lens' or t'Traversal' into a data structure -- according to the given 'Strategy'. -- -- @@@ -30,44 +37,44 @@ -- @ -- -- @--- 'evalOf' :: 'Simple' 'Lens' a b -> 'Strategy' b -> 'Strategy' a--- 'evalOf' :: 'Simple' 'Traversal' a b -> 'Strategy' b -> 'Strategy' a--- 'evalOf' :: (b -> 'Eval' b) -> a -> 'Eval' a) -> 'Strategy' b -> 'Strategy' a+-- 'evalOf' :: 'Lens'' s a -> 'Strategy' a -> 'Strategy' s+-- 'evalOf' :: 'Traversal'' s a -> 'Strategy' a -> 'Strategy' s+-- 'evalOf' :: (a -> 'Eval' a) -> s -> 'Eval' s) -> 'Strategy' a -> 'Strategy' s -- @-evalOf :: SimpleLensLike Eval a b -> Strategy b -> Strategy a+evalOf :: LensLike' Eval s a -> Strategy a -> Strategy s evalOf l = l {-# INLINE evalOf #-} --- | Evaluate the targets of a 'Lens' or 'Traversal' according into a+-- | Evaluate the targets of a t'Lens' or t'Traversal' according into a -- data structure according to a given 'Strategy' in parallel. -- -- @'parTraversable' = 'parOf' 'traverse'@ -- -- @--- 'parOf' :: 'Simple' 'Lens' a b -> 'Strategy' b -> 'Strategy' a--- 'parOf' :: 'Simple' 'Traversal' a b -> 'Strategy' b -> 'Strategy' a--- 'parOf' :: ((b -> 'Eval' b) -> a -> 'Eval' a) -> 'Strategy' b -> 'Strategy' a+-- 'parOf' :: 'Lens'' s a -> 'Strategy' a -> 'Strategy' s+-- 'parOf' :: 'Traversal'' s a -> 'Strategy' a -> 'Strategy' s+-- 'parOf' :: ((a -> 'Eval' a) -> s -> 'Eval' s) -> 'Strategy' a -> 'Strategy' s -- @-parOf :: SimpleLensLike Eval a b -> Strategy b -> Strategy a+parOf :: LensLike' Eval s a -> Strategy a -> Strategy s parOf l s = l (rparWith s) {-# INLINE parOf #-} --- | Transform a 'Lens', 'Fold', 'Getter', 'Setter' or 'Traversal' to+-- | Transform a t'Lens', t'Fold', t'Getter', t'Setter' or t'Traversal' to -- first evaluates its argument according to a given 'Strategy' /before/ proceeding. -- -- @ -- 'after' 'rdeepseq' 'traverse' :: 'Traversable' t => 'Strategy' a -> 'Strategy' [a] -- @-after :: Strategy a -> LensLike f a b c d -> LensLike f a b c d+after :: Strategy s -> LensLike f s t a b -> LensLike f s t a b after s l f = l f $| s {-# INLINE after #-} --- | Transform a 'Lens', 'Fold', 'Getter', 'Setter' or 'Traversal' to+-- | Transform a t'Lens', t'Fold', t'Getter', t'Setter' or t'Traversal' to -- evaluate its argument according to a given 'Strategy' /in parallel with/ evaluating. -- -- @ -- 'throughout' 'rdeepseq' 'traverse' :: 'Traversable' t => 'Strategy' a -> 'Strategy' [a] -- @-throughout :: Strategy a -> LensLike f a b c d -> LensLike f a b c d+throughout :: Strategy s -> LensLike f s t a b -> LensLike f s t a b throughout s l f = l f $|| s {-# INLINE throughout #-}
src/Control/Seq/Lens.hs view
@@ -1,13 +1,13 @@ ----------------------------------------------------------------------------- -- | -- Module      :  Control.Seq.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional -- Portability :  portable ----- A 'Fold' can be used to take the role of 'Foldable' in @Control.Seq@+-- A t'Fold' can be used to take the role of 'Foldable' in @Control.Seq@. ---------------------------------------------------------------------------- module Control.Seq.Lens   ( seqOf@@ -15,11 +15,12 @@  import Control.Lens import Control.Seq+import Data.Monoid --- | Evaluate the elements targeted by a 'Lens', 'Traversal', 'Iso',--- 'Getter' or 'Fold' according to the given strategy.+-- | Evaluate the elements targeted by a t'Lens', t'Traversal', t'Iso',+-- t'Getter' or t'Fold' according to the given strategy. -- -- @'seqFoldable' = 'seqOf' 'folded'@-seqOf :: Getting [c] a b c d -> Strategy c -> Strategy a+seqOf :: Getting (Endo [a]) s a -> Strategy a -> Strategy s seqOf l s = seqList s . toListOf l {-# INLINE seqOf #-}
src/Data/Array/Lens.hs view
@@ -1,10 +1,8 @@-{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE Rank2Types #-}-{-# LANGUAGE LiberalTypeSynonyms #-} ----------------------------------------------------------------------------- -- | -- Module      :  Data.Array.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional@@ -13,52 +11,24 @@ ---------------------------------------------------------------------------- module Data.Array.Lens   (-  -- * Indexing-    ix   -- * Setters-  , ixmapped-  -- * Traversal-  , traverseArray+    ixmapped   ) where -import Control.Applicative import Control.Lens import Data.Array.IArray hiding (index) --- | Access an element of an array.------ Note: The indexed element is assumed to exist in the target 'IArray'.------ @--- arr '!' i ≡ arr '^.' 'ix' i--- arr '//' [(i,e)] ≡ 'ix' i '.~' e '$' arr--- @------ >>> ix 2 .~ 9 $ (listArray (1,5) [4,5,6,7,8] :: Array Int Int)--- array (1,5) [(1,4),(2,9),(3,6),(4,7),(5,8)]-ix :: (IArray a e, Ix i) => i -> Simple Lens (a i e) e-ix i f arr = (\e -> arr // [(i,e)]) <$> f (arr ! i)-{-# INLINE ix #-}---- | This setter can be used to derive a new 'IArray' from an old array by+-- | This t'Setter' can be used to derive a new 'IArray' from an old 'IArray' by -- applying a function to each of the indices to look it up in the old 'IArray'. ----- This is a /contravariant/ 'Setter'.+-- This is a /contravariant/ t'Setter'. -- -- @--- 'ixmap' ≡ 'over' . 'ixmapped'--- 'ixmapped' ≡ 'sets' . 'ixmap'+-- 'ixmap' ≡ 'over' '.' 'ixmapped'+-- 'ixmapped' ≡ 'setting' '.' 'ixmap' -- 'over' ('ixmapped' b) f arr '!' i ≡ arr '!' f i -- 'bounds' ('over' ('ixmapped' b) f arr) ≡ b -- @-ixmapped :: (IArray a e, Ix i, Ix j) => (i,i) -> Setter (a j e) (a i e) i j-ixmapped = sets . ixmap+ixmapped :: (IArray a e, Ix i, Ix j) => (i,i) -> IndexPreservingSetter (a j e) (a i e) i j+ixmapped i = setting $ ixmap i {-# INLINE ixmapped #-}---- | An 'IndexedTraversal' of the elements of an 'IArray', using the--- index into the array as the index of the traversal.------ @'amap' ≡ 'over' 'traverseArray'@-traverseArray :: (IArray a c, IArray a d, Ix i) => IndexedTraversal i (a i c) (a i d) c d-traverseArray = index $ \f arr -> array (bounds arr) <$> traverse (\(i,a) -> (,) i <$> f i a) (assocs arr)-{-# INLINE traverseArray #-}
src/Data/Bits/Lens.hs view
@@ -1,10 +1,10 @@-{-# LANGUAGE LiberalTypeSynonyms #-}-{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE Rank2Types #-}+{-# LANGUAGE FlexibleContexts #-}+ ----------------------------------------------------------------------------- -- | -- Module      :  Data.Bits.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  experimental@@ -12,155 +12,292 @@ -- ---------------------------------------------------------------------------- module Data.Bits.Lens-  ( (|~), (&~), (<|~), (<&~)-  , (|=), (&=), (<|=), (<&=)+  ( (.|.~), (.&.~), (<.|.~), (<.&.~), (<<.|.~), (<<.&.~)+  , (.|.=), (.&.=), (<.|.=), (<.&.=), (<<.|.=), (<<.&.=)   , bitAt-  , traverseBits+  , bits+  , byteAt+  , bytewise   ) where +import Prelude ()+ import Control.Lens-import Control.Monad.State.Class+import Control.Lens.Internal.Prelude+import Control.Monad.State import Data.Bits-import Data.Functor+import Data.Word -infixr 4 |~, &~, <|~, <&~-infix 4 |=, &=, <|=, <&=+-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import Control.Monad.State+-- >>> import Data.Word --- | Bitwise '.|.' the target(s) of a 'Lens' or 'Setter'+infixr 4 .|.~, .&.~, <.|.~, <.&.~, <<.|.~, <<.&.~+infix 4 .|.=, .&.=, <.|.=, <.&.=, <<.|.=, <<.&.=++-- | Bitwise '.|.' the target(s) of a t'Lens' or t'Setter'. ----- >>> _2 |~ 6 $ ("hello",3)+-- >>> _2 .|.~ 6 $ ("hello",3) -- ("hello",7) -- -- @--- ('|~') :: 'Bits' c => 'Setter' a b c c -> c -> a -> b--- ('|~') :: 'Bits' c => 'Iso' a b c c -> c -> a -> b--- ('|~') :: 'Bits' c => 'Lens' a b c c -> c -> a -> b--- ('|~') :: ('Monoid c', 'Bits' c) => 'Traversal' a b c c -> c -> a -> b+-- ('.|.~') :: 'Bits' a             => t'Setter' s t a a    -> a -> s -> t+-- ('.|.~') :: 'Bits' a             => t'Iso' s t a a       -> a -> s -> t+-- ('.|.~') :: 'Bits' a             => t'Lens' s t a a      -> a -> s -> t+-- ('.|.~') :: ('Data.Monoid.Monoid' a, 'Bits' a) => t'Traversal' s t a a -> a -> s -> t -- @-(|~):: Bits c => Setting a b c c -> c -> a -> b-l |~ n = over l (.|. n)-{-# INLINE (|~) #-}+(.|.~):: Bits a => ASetter s t a a -> a -> s -> t+l .|.~ n = over l (.|. n)+{-# INLINE (.|.~) #-} --- | Bitwise '.&.' the target(s) of a 'Lens' or 'Setter'+-- | Bitwise '.&.' the target(s) of a t'Lens' or t'Setter'. ----- >>> _2 &~ 7 $ ("hello",254)+-- >>> _2 .&.~ 7 $ ("hello",254) -- ("hello",6) -- -- @--- ('&~') :: 'Bits' c => 'Setter' a b c c -> c -> a -> b--- ('&~') :: 'Bits' c => 'Iso' a b c c -> c -> a -> b--- ('&~') :: 'Bits' c => 'Lens' a b c c -> c -> a -> b--- ('&~') :: ('Monoid c', 'Bits' c) => 'Traversal' a b c c -> c -> a -> b+-- ('.&.~') :: 'Bits' a             => t'Setter' s t a a    -> a -> s -> t+-- ('.&.~') :: 'Bits' a             => t'Iso' s t a a       -> a -> s -> t+-- ('.&.~') :: 'Bits' a             => t'Lens' s t a a      -> a -> s -> t+-- ('.&.~') :: ('Data.Monoid.Monoid' a, 'Bits' a) => t'Traversal' s t a a -> a -> s -> t -- @-(&~) :: Bits c => Setting a b c c -> c -> a -> b-l &~ n = over l (.&. n)-{-# INLINE (&~) #-}+(.&.~) :: Bits a => ASetter s t a a -> a -> s -> t+l .&.~ n = over l (.&. n)+{-# INLINE (.&.~) #-} --- | Modify the target(s) of a 'Simple' 'Lens', 'Setter' or 'Traversal' by computing its bitwise '.&.' with another value.+-- | Modify the target(s) of a 'Lens'', 'Setter'' or 'Traversal'' by computing its bitwise '.&.' with another value. --+-- >>> execState (do _1 .&.= 15; _2 .&.= 3) (7,7)+-- (7,3)+-- -- @--- ('&=') :: ('MonadState' a m, 'Bits' b) => 'Simple' 'Setter' a b -> b -> m ()--- ('&=') :: ('MonadState' a m, 'Bits' b) => 'Simple' 'Iso' a b -> b -> m ()--- ('&=') :: ('MonadState' a m, 'Bits' b) => 'Simple' 'Lens' a b -> b -> m ()--- ('&=') :: ('MonadState' a m, 'Bits' b) => 'Simple' 'Traversal' a b -> b -> m ()+-- ('.&.=') :: ('MonadState' s m, 'Bits' a) => 'Setter'' s a    -> a -> m ()+-- ('.&.=') :: ('MonadState' s m, 'Bits' a) => 'Iso'' s a       -> a -> m ()+-- ('.&.=') :: ('MonadState' s m, 'Bits' a) => 'Lens'' s a      -> a -> m ()+-- ('.&.=') :: ('MonadState' s m, 'Bits' a) => 'Traversal'' s a -> a -> m () -- @-(&=):: (MonadState a m, Bits b) => Simple Setting a b -> b -> m ()-l &= b = modify (l &~ b)-{-# INLINE (&=) #-}+(.&.=):: (MonadState s m, Bits a) => ASetter' s a -> a -> m ()+l .&.= a = modify (l .&.~ a)+{-# INLINE (.&.=) #-} --- | Modify the target(s) of a 'Simple' 'Lens', 'Setter' or 'Traversal' by computing its bitwise '.|.' with another value.+-- | Modify the target(s) of a 'Lens'', t'Setter' or t'Traversal' by computing its bitwise '.|.' with another value. --+-- >>> execState (do _1 .|.= 15; _2 .|.= 3) (7,7)+-- (15,7)+-- -- @--- ('|=') :: ('MonadState' a m, 'Bits' b) => 'Simple' 'Setter' a b -> b -> m ()--- ('|=') :: ('MonadState' a m, 'Bits' b) => 'Simple' 'Iso' a b -> b -> m ()--- ('|=') :: ('MonadState' a m, 'Bits' b) => 'Simple' 'Lens' a b -> b -> m ()--- ('|=') :: ('MonadState' a m, 'Bits' b) => 'Simple' 'Traversal' a b -> b -> m ()+-- ('.|.=') :: ('MonadState' s m, 'Bits' a) => 'Setter'' s a    -> a -> m ()+-- ('.|.=') :: ('MonadState' s m, 'Bits' a) => 'Iso'' s a       -> a -> m ()+-- ('.|.=') :: ('MonadState' s m, 'Bits' a) => 'Lens'' s a      -> a -> m ()+-- ('.|.=') :: ('MonadState' s m, 'Bits' a) => 'Traversal'' s a -> a -> m () -- @-(|=) :: (MonadState a m, Bits b) => Simple Setting a b -> b -> m ()-l |= b = modify (l |~ b)-{-# INLINE (|=) #-}+(.|.=) :: (MonadState s m, Bits a) => ASetter' s a -> a -> m ()+l .|.= a = modify (l .|.~ a)+{-# INLINE (.|.=) #-} --- | Bitwise '.|.' the target(s) of a 'Lens' (or 'Traversal'), returning the result+-- | Bitwise '.|.' the target(s) of a t'Lens' (or t'Traversal'), returning the result -- (or a monoidal summary of all of the results). ----- >>> _2 <|~ 6 $ ("hello",3)+-- >>> _2 <.|.~ 6 $ ("hello",3) -- (7,("hello",7)) -- -- @--- ('<|~') :: 'Bits' c => 'Iso' a b c c -> c -> a -> (c, b)--- ('<|~') :: 'Bits' c => 'Lens' a b c c -> c -> a -> (c, b)--- ('<|~') :: ('Bits' c, 'Monoid c) => 'Traversal' a b c c -> c -> a -> (c, b)+-- ('<.|.~') :: 'Bits' a             => t'Iso' s t a a       -> a -> s -> (a, t)+-- ('<.|.~') :: 'Bits' a             => t'Lens' s t a a      -> a -> s -> (a, t)+-- ('<.|.~') :: ('Bits' a, 'Data.Monoid.Monoid' a) => t'Traversal' s t a a -> a -> s -> (a, t) -- @-(<|~):: Bits c => LensLike ((,) c) a b c c -> c -> a -> (c, b)-l <|~ n = l <%~ (.|. n)-{-# INLINE (<|~) #-}+(<.|.~):: Bits a => LensLike ((,) a) s t a a -> a -> s -> (a, t)+l <.|.~ n = l <%~ (.|. n)+{-# INLINE (<.|.~) #-} --- | Bitwise '.&.' the target(s) of a 'Lens' or 'Traversal', returning the result+-- | Bitwise '.&.' the target(s) of a t'Lens' or t'Traversal', returning the result -- (or a monoidal summary of all of the results). ----- >>> _2 <&~ 7 $ ("hello",254)+-- >>> _2 <.&.~ 7 $ ("hello",254) -- (6,("hello",6)) -- -- @--- ('<&~') :: 'Bits' c => 'Iso' a b c c -> c -> a -> (c, b)--- ('<&~') :: 'Bits' c => 'Lens' a b c c -> c -> a -> (c, b)--- ('<&~') :: ('Bits' c, 'Monoid c) => 'Traversal' a b c c -> c -> a -> (c, b)+-- ('<.&.~') :: 'Bits' a             => t'Iso'       s t a a -> a -> s -> (a, t)+-- ('<.&.~') :: 'Bits' a             => t'Lens'      s t a a -> a -> s -> (a, t)+-- ('<.&.~') :: ('Bits' a, 'Data.Monoid.Monoid' a) => t'Traversal' s t a a -> a -> s -> (a, t) -- @-(<&~) :: Bits c => LensLike ((,) c) a b c c -> c -> a -> (c, b)-l <&~ n = l <%~ (.&. n)-{-# INLINE (<&~) #-}+(<.&.~) :: Bits a => LensLike ((,) a) s t a a -> a -> s -> (a, t)+l <.&.~ n = l <%~ (.&. n)+{-# INLINE (<.&.~) #-} --- | Modify the target(s) of a 'Simple' 'Lens' (or 'Traversal') by computing its bitwise '.&.' with another value,--- returning the result (or a monoidal summary of all of the results traversed)+-- | Modify the target(s) of a 'Lens'' (or 'Traversal'') by computing its bitwise '.&.' with another value,+-- returning the result (or a monoidal summary of all of the results traversed). --+-- >>> runState (_1 <.&.= 15) (31,0)+-- (15,(15,0))+-- -- @--- ('<&=') :: ('MonadState' a m, 'Bits' b) => 'Simple' 'Lens' a b -> b -> m b--- ('<&=') :: ('MonadState' a m, 'Bits' b, 'Monoid' b) => 'Simple' 'Traversal' a b -> b -> m b+-- ('<.&.=') :: ('MonadState' s m, 'Bits' a)           => 'Lens'' s a      -> a -> m a+-- ('<.&.=') :: ('MonadState' s m, 'Bits' a, 'Data.Monoid.Monoid' a) => 'Traversal'' s a -> a -> m a -- @-(<&=):: (MonadState a m, Bits b) => SimpleLensLike ((,)b) a b -> b -> m b-l <&= b = l <%= (.&. b)-{-# INLINE (<&=) #-}+(<.&.=):: (MonadState s m, Bits a) => LensLike' ((,)a) s a -> a -> m a+l <.&.= b = l <%= (.&. b)+{-# INLINE (<.&.=) #-} --- | Modify the target(s) of a 'Simple' 'Lens', (or 'Traversal') by computing its bitwise '.|.' with another value,--- returning the result (or a monoidal summary of all of the results traversed)+-- | Modify the target(s) of a 'Lens'', (or t'Traversal') by computing its bitwise '.|.' with another value,+-- returning the result (or a monoidal summary of all of the results traversed). --+-- >>> runState (_1 <.|.= 7) (28,0)+-- (31,(31,0))+-- -- @--- ('<|=') :: ('MonadState' a m, 'Bits' b) => 'Simple' 'Lens' a b -> b -> m b--- ('<|=') :: ('MonadState' a m, 'Bits' b, 'Monoid' b) => 'Simple' 'Traversal' a b -> b -> m b+-- ('<.|.=') :: ('MonadState' s m, 'Bits' a)           => 'Lens'' s a      -> a -> m a+-- ('<.|.=') :: ('MonadState' s m, 'Bits' a, 'Data.Monoid.Monoid' a) => 'Traversal'' s a -> a -> m a -- @-(<|=) :: (MonadState a m, Bits b) => SimpleLensLike ((,)b) a b -> b -> m b-l <|= b = l <%= (.|. b)-{-# INLINE (<|=) #-}+(<.|.=) :: (MonadState s m, Bits a) => LensLike' ((,)a) s a -> a -> m a+l <.|.= b = l <%= (.|. b)+{-# INLINE (<.|.=) #-} --- | This lens can be used to access the value of the nth bit in a number.+-- | Bitwise '.&.' the target(s) of a t'Lens' or t'Traversal', and return the+-- original value, or a monoidal summary of the original values. ----- @'bitAt' n@ is only a legal 'Lens' into @b@ if @0 <= n < 'bitSize' ('undefined' :: b)@+-- When you do not need the old value, ('.&.~') is more flexible. --+-- >>> _2 <<.&.~ 7 $ ("hello", 254)+-- (254,("hello",6))+--+-- @+-- ('<<.&.~') ::  'Bits' a            => t'Iso' s t a a       -> a -> s -> (a, t)+-- ('<<.&.~') ::  'Bits' a            => t'Lens' s t a a      -> a -> s -> (a, t)+-- ('<<.&.~') :: ('Bits' a, 'Data.Monoid.Monoid' a) => t'Traversal' s t a a -> a -> s -> (a, t)+-- @+(<<.&.~) :: Bits a => Optical' (->) q ((,)a) s a -> a -> q s (a, s)+l <<.&.~ b = l $ \a -> (a, a .&. b)+{-# INLINE (<<.&.~) #-}++-- | Bitwise '.|.' the target(s) of a t'Lens' or t'Traversal', and return the+-- original value, or a monoidal summary of the original values.+--+-- When you do not need the old value, ('.|.~') is more flexible.+--+-- >>> _2 <<.|.~ 6 $ ("hello", 3)+-- (3,("hello",7))+--+-- @+-- ('<<.|.~') ::  'Bits' a            => t'Iso' s t a a       -> a -> s -> (a, t)+-- ('<<.|.~') ::  'Bits' a            => t'Lens' s t a a      -> a -> s -> (a, t)+-- ('<<.|.~') :: ('Bits' a, 'Data.Monoid.Monoid' a) => t'Traversal' s t a a -> a -> s -> (a, t)+-- @+(<<.|.~) :: Bits a => Optical' (->) q ((,)a) s a -> a -> q s (a, s)+l <<.|.~ b = l $ \a -> (a, a .|. b)+{-# INLINE (<<.|.~) #-}++-- | Modify the target(s) of a 'Lens'', (or 'Traversal'') by computing its+-- bitwise '.&.' with another value, returning the original value (or a+-- monoidal summary of all the original values).+--+-- When you do not need the old value, ('.&.=') is more flexible.+--+-- >>> runState (_1 <<.&.= 15) (31,0)+-- (31,(15,0))+--+-- @+-- ('<<.&.=') :: ('MonadState' s m, 'Bits' a)           => 'Lens'' s a      -> a -> m a+-- ('<<.&.=') :: ('MonadState' s m, 'Bits' a, 'Data.Monoid.Monoid' a) => 'Traversal'' s a -> a -> m a+-- @+(<<.&.=) :: (MonadState s m, Bits a) => LensLike' ((,) a) s a -> a -> m a+l <<.&.= b = l %%= \a -> (a, a .&. b)+{-# INLINE (<<.&.=) #-}++-- | Modify the target(s) of a 'Lens'', (or 'Traversal'') by computing its+-- bitwise '.|.' with another value, returning the original value (or a+-- monoidal summary of all the original values).+--+-- When you do not need the old value, ('.|.=') is more flexible.+--+-- >>> runState (_1 <<.|.= 7) (28,0)+-- (28,(31,0))+--+-- @+-- ('<<.|.=') :: ('MonadState' s m, 'Bits' a)           => 'Lens'' s a      -> a -> m a+-- ('<<.|.=') :: ('MonadState' s m, 'Bits' a, 'Data.Monoid.Monoid' a) => 'Traversal'' s a -> a -> m a+-- @+(<<.|.=) :: (MonadState s m, Bits a) => LensLike' ((,) a) s a -> a -> m a+l <<.|.= b = l %%= \a -> (a, a .|. b)+{-# INLINE (<<.|.=) #-}++-- | This t'Lens' can be used to access the value of the nth bit in a number.+--+-- @'bitAt' n@ is only a legal t'Lens' into @b@ if @0 '<=' n '<' 'bitSize' ('undefined' :: b)@.+-- -- >>> 16^.bitAt 4 -- True -- -- >>> 15^.bitAt 4 -- False-bitAt :: Bits b => Int -> SimpleIndexedLens Int b Bool-bitAt n = index $ \f b -> (\x -> if x then setBit b n else clearBit b n) <$> f n (testBit b n)+--+-- >>> 15 & bitAt 4 .~ True+-- 31+--+-- >>> 16 & bitAt 4 .~ False+-- 0+bitAt :: Bits b => Int -> IndexedLens' Int b Bool+bitAt n f b = indexed f n (testBit b n) <&> \x -> if x then setBit b n else clearBit b n {-# INLINE bitAt #-} +-- | Get the nth byte, counting from the low end.+--+-- @'byteAt' n@ is a legal t'Lens' into @b@ iff @0 '<=' n '<' 'div' ('bitSize' ('undefined' :: b)) 8@+--+-- >>> (0xff00 :: Word16)^.byteAt 0+-- 0+--+-- >>> (0xff00 :: Word16)^.byteAt 1+-- 255+--+-- >>> byteAt 1 .~ 0 $ 0xff00 :: Word16+-- 0+--+-- >>> byteAt 0 .~ 0xff $ 0 :: Word16+-- 255+byteAt :: (Integral b, Bits b) => Int -> IndexedLens' Int b Word8+byteAt i f b = back <$> indexed f i (forward b) where+  back w8 = (fromIntegral w8 `shiftL` (i * 8))+    .|. (complement (255 `shiftL` (i * 8)) .&. b)+  forward = fromIntegral . (.&.) 0xff . flip shiftR (i * 8)++ -- | Traverse over all bits in a numeric type. -- -- The bit position is available as the index. ----- >>> import Data.Word--- >>> toListOf traverseBits (5 :: Word8)+-- >>> toListOf bits (5 :: Word8) -- [True,False,True,False,False,False,False,False] ----- If you supply this an 'Integer', the result will--- be an infinite 'Traversal' that can be productively consumed.-traverseBits :: (Num b, Bits b) => SimpleIndexedTraversal Int b Bool-traverseBits = index $ \f b -> let-    g n      = (,) n <$> f n (testBit b n)-    bits     = Prelude.takeWhile hasBit [0..]-    hasBit n = complementBit b n /= b -- test to make sure that complementing this bit actually changes the value-    step (n,True) r = setBit r n-    step _        r = r-  in Prelude.foldr step 0 <$> traverse g bits-{-# INLINE traverseBits #-}+-- If you supply this an 'Integer', the result will be an infinite t'Traversal', which+-- can be productively consumed, but not reassembled.+bits :: (Num b, Bits b) => IndexedTraversal' Int b Bool+bits f b = foldr step 0 <$> traverse g bs where+  g n      = (,) n <$> indexed f n (testBit b n)+  bs       = takeWhile hasBit [0..]+  hasBit n = complementBit b n /= b -- test to make sure that complementing this bit actually changes the value+  step (n,True) r = setBit r n+  step _        r = r+{-# INLINE bits #-}++-- | Traverse over all the bytes in an integral type, from the low end.+--+-- The byte position is available as the index.+--+-- >>> toListOf bytewise (1312301580 :: Word32)+-- [12,34,56,78]+--+-- If you supply this an 'Integer', the result will be an infinite t'Traversal',+-- which can be productively consumed, but not reassembled.+--+-- Why isn't this function called @bytes@ to match 'bits'? Alas, there+-- is already a function by that name in "Data.ByteString.Lens".+bytewise :: (Integral b, Bits b) => IndexedTraversal' Int b Word8+bytewise f b = foldr step 0 <$> traverse g bs where+  g n = (,) n <$> indexed f n (fromIntegral $ b `shiftR` (n*8))+  bs = takeWhile hasByte [0..]+  hasByte n = complementBit b (n*8) /= b+  step (n,x) r = r .|. (fromIntegral x `shiftL` (n*8))+{-# INLINE bytewise #-}
src/Data/ByteString/Lazy/Lens.hs view
@@ -1,64 +1,146 @@+{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE ViewPatterns #-}+{-# LANGUAGE PatternSynonyms #-}+ ----------------------------------------------------------------------------- -- | -- Module      :  Data.ByteString.Lazy.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-2016 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  portable+-- Stability   :  experimental+-- Portability :  non-portable ----- Lenses for lazy bytestrings+-- Lazy 'ByteString' lenses. ---------------------------------------------------------------------------- module Data.ByteString.Lazy.Lens-  ( packedBytes, bytes-  , packedChars, chars+  ( packedBytes, unpackedBytes, bytes+  , packedChars, unpackedChars, chars+  , pattern Bytes+  , pattern Chars   ) where  import Control.Lens-import Data.ByteString.Lazy as Words-import Data.ByteString.Lazy.Char8 as Char8-import Data.List.Lens+import Control.Lens.Internal.ByteString+import Data.ByteString.Lazy (ByteString)+import qualified Data.ByteString.Lazy       as Words+import qualified Data.ByteString.Lazy.Char8 as Char8 import Data.Word (Word8)+import Data.Int (Int64) --- | 'Data.ByteString.Lazy.pack' (or 'Data.ByteString.Lazy.unpack') a list of bytes into a 'ByteString'+-- $setup+-- >>> :set -XOverloadedStrings+-- >>> import Control.Lens+-- >>> import Numeric.Lens+-- >>> import qualified Data.ByteString.Lazy.Char8 as Char8++-- | 'Data.ByteString.Lazy.pack' (or 'Data.ByteString.Lazy.unpack') a list of bytes into a 'ByteString'. ----- @'Data.ByteString.Lazy.pack' x = x '^.' 'packedBytes'@+-- @+-- 'packedBytes' ≡ 'from' 'unpackedBytes'+-- 'Data.ByteString.pack' x ≡  x '^.' 'packedBytes'+-- 'Data.ByteString.unpack' x ≡ x '^.' 'from' 'packedBytes'+-- @ ----- @'Data.ByteString.Lazy.unpack' x = x '^.' 'from' 'packedBytes'@-packedBytes :: Simple Iso [Word8] ByteString+-- >>> [104,101,108,108,111]^.packedBytes == Char8.pack "hello"+-- True+packedBytes :: Iso' [Word8] ByteString packedBytes = iso Words.pack Words.unpack {-# INLINE packedBytes #-} --- | Traverse the individual bytes in a 'ByteString'+-- | 'Data.ByteString.Lazy.unpack' (or 'Data.ByteString.Lazy.pack') a 'ByteString' into a list of bytes ----- @'bytes' = 'from' 'packedBytes' . 'traverseList'@+-- @+-- 'unpackedBytes' ≡ 'from' 'packedBytes'+-- 'Data.ByteString.unpack' x ≡ x '^.' 'unpackedBytes'+-- 'Data.ByteString.pack' x ≡  x '^.' 'from' 'unpackedBytes'+-- @ ----- @'anyOf' 'bytes' ('==' 0x80) :: 'ByteString' -> 'Bool'@-bytes :: SimpleIndexedTraversal Int ByteString Word8-bytes = from packedBytes .> traverseList+-- >>> "hello"^.packedChars.unpackedBytes+-- [104,101,108,108,111]+unpackedBytes :: Iso' ByteString [Word8]+unpackedBytes = from packedBytes+{-# INLINE unpackedBytes #-}++-- | Traverse the individual bytes in a 'ByteString'.+--+-- This t'Traversal' walks each strict 'ByteString' chunk in a tree-like fashion+-- enable zippers to seek to locations more quickly and accelerate+-- many monoidal queries, but up to associativity (and constant factors) it is+-- equivalent to the much slower:+--+-- @+-- 'bytes' ≡ 'unpackedBytes' '.' 'traversed'+-- @+--+-- >>> anyOf bytes (== 0x80) (Char8.pack "hello")+-- False+--+-- Note that when just using this as a t'Setter', @'setting' 'Data.ByteString.Lazy.map'@+-- can be more efficient.+bytes :: IndexedTraversal' Int64 ByteString Word8+bytes = traversedLazy {-# INLINE bytes #-} --- | 'Data.ByteString.Lazy.Char8.pack' (or 'Data.ByteString.Lazy.Char8.unpack') a list of characters into a 'ByteString'+-- | 'Data.ByteString.Lazy.Char8.pack' (or 'Data.ByteString.Lazy.Char8.unpack') a list of characters into a 'ByteString'. -- -- When writing back to the 'ByteString' it is assumed that every 'Char'--- lies between '\x00' and '\xff'.+-- lies between @'\x00'@ and @'\xff'@. ----- @'Data.ByteString.Lazy.Char8.pack' x = x '^.' 'packedChars'@+-- @+-- 'packedChars' ≡ 'from' 'unpackedChars'+-- 'Data.ByteString.Char8.pack' x ≡ x '^.' 'packedChars'+-- 'Data.ByteString.Char8.unpack' x ≡ x '^.' 'from' 'packedChars'+-- @ ----- @'Data.ByteString.Lazy.Char8.unpack' x = x '^.' 'from' 'packedChars'@-packedChars :: Simple Iso String ByteString+-- >>> "hello"^.packedChars.each.re (base 16 . enum).to (\x -> if Prelude.length x == 1 then '0':x else x)+-- "68656c6c6f"+packedChars :: Iso' String ByteString packedChars = iso Char8.pack Char8.unpack {-# INLINE packedChars #-} +-- | 'Data.ByteString.Lazy.Char8.unpack' (or 'Data.ByteString.Lazy.Char8.pack') a list of characters into a 'ByteString'+--+-- When writing back to the 'ByteString' it is assumed that every 'Char'+-- lies between @'\x00'@ and @'\xff'@.+--+-- @+-- 'unpackedChars' ≡ 'from' 'packedChars'+-- 'Data.ByteString.Char8.unpack' x ≡ x '^.' 'unpackedChars'+-- 'Data.ByteString.Char8.pack' x ≡ x '^.' 'from' 'unpackedChars'+-- @+--+-- >>> [104,101,108,108,111]^.packedBytes.unpackedChars+-- "hello"+unpackedChars :: Iso' ByteString String+unpackedChars = from packedChars+{-# INLINE unpackedChars #-}+ -- | Traverse the individual bytes in a 'ByteString' as characters. -- -- When writing back to the 'ByteString' it is assumed that every 'Char'--- lies between '\x00' and '\xff'.+-- lies between @'\x00'@ and @'\xff'@. ----- @'chars' = 'from' 'packedChars' '.>' 'traverseList'@+-- This t'Traversal' walks each strict 'ByteString' chunk in a tree-like fashion+-- enable zippers to seek to locations more quickly and accelerate+-- many monoidal queries, but up to associativity (and constant factors) it is+-- equivalent to: ----- @'anyOf' 'chars' ('==' \'c\') :: 'ByteString' -> 'Bool'@-chars :: SimpleIndexedTraversal Int ByteString Char-chars = from packedChars .> traverseList+-- @+-- 'chars' = 'unpackedChars' '.' 'traversed'+-- @+--+-- >>> anyOf chars (== 'h') "hello"+-- True+chars :: IndexedTraversal' Int64 ByteString Char+chars = traversedLazy8 {-# INLINE chars #-}++pattern Bytes :: [Word8] -> ByteString+pattern Bytes b <- (view unpackedBytes -> b) where+  Bytes b = review unpackedBytes b++pattern Chars :: String -> ByteString+pattern Chars b <- (view unpackedChars -> b) where+  Chars b = review unpackedChars b
src/Data/ByteString/Lens.hs view
@@ -1,65 +1,138 @@+{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE ViewPatterns #-}+{-# LANGUAGE PatternSynonyms #-} ----------------------------------------------------------------------------- -- | -- Module      :  Data.ByteString.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  portable+-- Stability   :  experimental+-- Portability :  non-portable -- ---------------------------------------------------------------------------- module Data.ByteString.Lens   ( IsByteString(..)+  , unpackedBytes+  , unpackedChars+  , pattern Bytes+  , pattern Chars   ) where  import           Control.Lens import           Data.Word (Word8)-import           Data.ByteString as Strict+import qualified Data.ByteString as Strict import qualified Data.ByteString.Strict.Lens as Strict-import           Data.ByteString.Lazy as Lazy+import qualified Data.ByteString.Lazy as Lazy import qualified Data.ByteString.Lazy.Lens as Lazy  -- | Traversals for ByteStrings. class IsByteString t where-  -- | 'Data.ByteString.pack' (or 'Data.ByteString.unpack') a list of bytes into a strict or lazy 'ByteString'-  ---  -- @'Data.ByteString.pack' x = x '^.' 'packedBytes'@+  -- | 'Data.ByteString.pack' (or 'Data.ByteString.unpack') a list of bytes into a strict or lazy 'ByteString'.   ---  -- @'Data.ByteString.unpack' x = x '^.' 'from' 'packedBytes'@-  packedBytes :: Simple Iso [Word8] t+  -- @+  -- 'Data.ByteString.pack' x ≡ x '^.' 'packedBytes'+  -- 'Data.ByteString.unpack' x ≡ x '^.' 'from' 'packedBytes'+  -- 'packedBytes' ≡ 'from' 'unpackedBytes'+  -- @+  packedBytes :: Iso' [Word8] t -  -- | 'Data.ByteString.Char8.pack' (or 'Data.ByteString.Char8.unpack') a list of characters into a strict or lazy 'ByteString'+  -- | 'Data.ByteString.Char8.pack' (or 'Data.ByteString.Char8.unpack') a list of characters into a strict or lazy 'ByteString'.   --   -- When writing back to the 'ByteString' it is assumed that every 'Char'-  -- lies between '\x00' and '\xff'.-  ---  -- @'Data.ByteString.Char8.pack' x = x '^.' 'packedChars'@+  -- lies between @'\x00'@ and @'\xff'@.   ---  -- @'Data.ByteString.Char8.unpack' x = x '^.' 'from' 'packedChars'@-  packedChars :: Simple Iso String t+  -- @+  -- 'Data.ByteString.Char8.pack' x ≡ x '^.' 'packedChars'+  -- 'Data.ByteString.Char8.unpack' x ≡ x '^.' 'from' 'packedChars'+  -- 'packedChars' ≡ 'from' 'unpackedChars'+  -- @+  packedChars :: Iso' String t    -- | Traverse each 'Word8' in a strict or lazy 'ByteString'   ---  -- @'bytes' = 'from' 'packedBytes' '.>' 'traverseList'@   ---  -- @'anyOf' 'bytes' ('==' 0x80) :: 'ByteString' -> 'Bool'@-  bytes :: SimpleIndexedTraversal Int t Word8-  bytes = from packedBytes .> itraversed+  -- This t'Traversal' walks each strict 'ByteString' chunk in a tree-like fashion+  -- enable zippers to seek to locations more quickly and accelerate+  -- many monoidal queries, but up to associativity (and constant factors) it is+  -- equivalent to the much slower:+  --+  -- @+  -- 'bytes' ≡ 'unpackedBytes' '.' 'traversed'+  -- @+  --+  -- @+  -- 'anyOf' 'bytes' ('==' 0x80) :: 'ByteString' -> 'Bool'+  -- @+  bytes :: IndexedTraversal' Int t Word8+  bytes = from packedBytes . traversed   {-# INLINE bytes #-}    -- | Traverse the individual bytes in a strict or lazy 'ByteString' as characters.   --   -- When writing back to the 'ByteString' it is assumed that every 'Char'-  -- lies between '\x00' and '\xff'.+  -- lies between @'\x00'@ and @'\xff'@.   ---  -- @'chars' = 'from' 'packedChars' . 'traverse'@+  -- This t'Traversal' walks each strict 'ByteString' chunk in a tree-like fashion+  -- enable zippers to seek to locations more quickly and accelerate+  -- many monoidal queries, but up to associativity (and constant factors) it is+  -- equivalent to the much slower:   ---  -- @'anyOf' 'chars' ('==' \'c\') :: 'ByteString' -> 'Bool'@-  chars :: SimpleIndexedTraversal Int t Char-  chars = from packedChars .> itraversed+  -- @+  -- 'chars' ≡ 'unpackedChars' '.' 'traversed'+  -- @+  --+  -- @+  -- 'anyOf' 'chars' ('==' \'c\') :: 'ByteString' -> 'Bool'+  -- @+  chars :: IndexedTraversal' Int t Char+  chars = from packedChars . traversed   {-# INLINE chars #-} +-- | 'Data.ByteString.unpack' (or 'Data.ByteString.pack') a 'ByteString' into a list of bytes+--+-- @+-- 'unpackedBytes' ≡ 'from' 'packedBytes'+-- 'Data.ByteString.unpack' x ≡ x '^.' 'unpackedBytes'+-- 'Data.ByteString.pack' x ≡  x '^.' 'from' 'unpackedBytes'+-- @+--+-- @+-- 'unpackedBytes' :: 'Iso'' 'Data.ByteString.ByteString' ['Word8']+-- 'unpackedBytes' :: 'Iso'' 'Data.ByteString.Lazy.ByteString' ['Word8']+-- @+unpackedBytes :: IsByteString t => Iso' t [Word8]+unpackedBytes = from packedBytes+{-# INLINE unpackedBytes #-}++pattern Bytes :: IsByteString s => [Word8] -> s+pattern Bytes b <- (view unpackedBytes -> b) where+  Bytes b = review unpackedBytes b++pattern Chars :: IsByteString s => String -> s+pattern Chars b <- (view unpackedChars -> b) where+  Chars b = review unpackedChars b++-- | 'Data.ByteString.Char8.unpack' (or 'Data.ByteString.Char8.pack') a list of characters into a strict (or lazy) 'ByteString'+--+-- When writing back to the 'ByteString' it is assumed that every 'Char'+-- lies between @'\x00'@ and @'\xff'@.+--+-- @+-- 'unpackedChars' ≡ 'from' 'packedChars'+-- 'Data.ByteString.Char8.unpack' x ≡ x '^.' 'unpackedChars'+-- 'Data.ByteString.Char8.pack' x ≡ x '^.' 'from' 'unpackedChars'+-- @+--+-- @+-- 'unpackedChars' :: 'Iso'' 'Data.ByteString.ByteString' 'String'+-- 'unpackedChars' :: 'Iso'' 'Data.ByteString.Lazy.ByteString' 'String'+-- @+unpackedChars :: IsByteString t => Iso' t String+unpackedChars = from packedChars+{-# INLINE unpackedChars #-}+ instance IsByteString Strict.ByteString where   packedBytes = Strict.packedBytes   {-# INLINE packedBytes #-}@@ -75,7 +148,7 @@   {-# INLINE packedBytes #-}   packedChars = Lazy.packedChars   {-# INLINE packedChars #-}-  bytes = Lazy.bytes+  bytes = from packedBytes . traversed   {-# INLINE bytes #-}-  chars = Lazy.chars+  chars = from packedChars . traversed   {-# INLINE chars #-}
src/Data/ByteString/Strict/Lens.hs view
@@ -1,63 +1,144 @@+{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE ViewPatterns #-}+{-# LANGUAGE PatternSynonyms #-}+ ----------------------------------------------------------------------------- -- | -- Module      :  Data.ByteString.Strict.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-2016 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  portable+-- Stability   :  experimental+-- Portability :  non-portable -- ---------------------------------------------------------------------------- module Data.ByteString.Strict.Lens-  ( packedBytes, bytes-  , packedChars, chars+  ( packedBytes, unpackedBytes, bytes+  , packedChars, unpackedChars, chars+  , pattern Bytes+  , pattern Chars   ) where  import Control.Lens-import Data.ByteString as Words-import Data.ByteString.Char8 as Char8-import Data.List.Lens-import Data.Word (Word8)+import Control.Lens.Internal.ByteString+import Data.ByteString (ByteString)+import qualified Data.ByteString       as Words+import qualified Data.ByteString.Char8 as Char8+import Data.Word +-- $setup+-- >>> :set -XOverloadedStrings+-- >>> import Control.Lens+-- >>> import Numeric.Lens+-- >>> import qualified Data.ByteString.Char8 as Char8+ -- | 'Data.ByteString.pack' (or 'Data.ByteString.unpack') a list of bytes into a 'ByteString' ----- @'Data.ByteString.pack' x = x '^.' 'packedBytes'@+-- @+-- 'packedBytes' ≡ 'from' 'unpackedBytes'+-- 'Data.ByteString.pack' x ≡  x '^.' 'packedBytes'+-- 'Data.ByteString.unpack' x ≡ x '^.' 'from' 'packedBytes'+-- @ ----- @'Data.ByteString.unpack' x = x '^.' 'from' 'packedBytes'@-packedBytes :: Simple Iso [Word8] ByteString+-- >>> [104,101,108,108,111]^.packedBytes+-- "hello"+packedBytes :: Iso' [Word8] ByteString packedBytes = iso Words.pack Words.unpack {-# INLINE packedBytes #-} --- | Traverse each 'Word8' in a 'ByteString'+-- | 'Data.ByteString.unpack' (or 'Data.ByteString.pack') a 'ByteString' into a list of bytes ----- @'bytes' = 'from' 'packedBytes' '.>' 'traverseList'@+-- @+-- 'unpackedBytes' ≡ 'from' 'packedBytes'+-- 'Data.ByteString.unpack' x ≡ x '^.' 'unpackedBytes'+-- 'Data.ByteString.pack' x ≡  x '^.' 'from' 'unpackedBytes'+-- @ ----- @'anyOf' 'bytes' ('==' 0x80) :: 'ByteString' -> 'Bool'@-bytes :: SimpleIndexedTraversal Int ByteString Word8-bytes = from packedBytes .> traverseList+-- >>> "hello"^.packedChars.unpackedBytes+-- [104,101,108,108,111]+unpackedBytes :: Iso' ByteString [Word8]+unpackedBytes = from packedBytes+{-# INLINE unpackedBytes #-}++-- | Traverse each 'Word8' in a 'ByteString'.+--+-- This t'Traversal' walks the 'ByteString' in a tree-like fashion+-- enable zippers to seek to locations in logarithmic time and accelerating+-- many monoidal queries, but up to associativity (and constant factors)+-- it is equivalent to the much slower:+--+-- @+-- 'bytes' ≡ 'unpackedBytes' '.' 'traversed'+-- @+--+-- >>> anyOf bytes (== 0x80) (Char8.pack "hello")+-- False+--+-- Note that when just using this as a t'Setter', @'setting' 'Data.ByteString.map'@+-- can be more efficient.+bytes :: IndexedTraversal' Int ByteString Word8+bytes = traversedStrictTree {-# INLINE bytes #-}  -- | 'Data.ByteString.Char8.pack' (or 'Data.ByteString.Char8.unpack') a list of characters into a 'ByteString' -- -- When writing back to the 'ByteString' it is assumed that every 'Char'--- lies between '\x00' and '\xff'.+-- lies between @'\x00'@ and @'\xff'@. ----- @'Data.ByteString.Char8.pack' x = x '^.' 'packedChars'@+-- @+-- 'packedChars' ≡ 'from' 'unpackedChars'+-- 'Data.ByteString.Char8.pack' x ≡ x '^.' 'packedChars'+-- 'Data.ByteString.Char8.unpack' x ≡ x '^.' 'from' 'packedChars'+-- @ ----- @'Data.ByteString.Char8.unpack' x = x '^.' 'from' 'packedChars'@-packedChars :: Simple Iso String ByteString+-- >>> "hello"^.packedChars.each.re (base 16 . enum).to (\x -> if Prelude.length x == 1 then '0':x else x)+-- "68656c6c6f"+packedChars :: Iso' String ByteString packedChars = iso Char8.pack Char8.unpack {-# INLINE packedChars #-} +-- | 'Data.ByteString.Char8.unpack' (or 'Data.ByteString.Char8.pack') a list of characters into a 'ByteString'+--+-- When writing back to the 'ByteString' it is assumed that every 'Char'+-- lies between @'\x00'@ and @'\xff'@.+--+-- @+-- 'unpackedChars' ≡ 'from' 'packedChars'+-- 'Data.ByteString.Char8.unpack' x ≡ x '^.' 'unpackedChars'+-- 'Data.ByteString.Char8.pack' x ≡ x '^.' 'from' 'unpackedChars'+-- @+--+-- >>> [104,101,108,108,111]^.packedBytes.unpackedChars+-- "hello"+unpackedChars :: Iso' ByteString String+unpackedChars = from packedChars+{-# INLINE unpackedChars #-}+ -- | Traverse the individual bytes in a 'ByteString' as characters. -- -- When writing back to the 'ByteString' it is assumed that every 'Char'--- lies between '\x00' and '\xff'.+-- lies between @'\x00'@ and @'\xff'@. ----- @'chars' = 'from' 'packedChars' . 'traverse'@+-- This t'Traversal' walks the 'ByteString' in a tree-like fashion+-- enable zippers to seek to locations in logarithmic time and accelerating+-- many monoidal queries, but up to associativity (and constant factors)+-- it is equivalent to the much slower: ----- @'anyOf' 'chars' ('==' \'c\') :: 'ByteString' -> 'Bool'@-chars :: SimpleIndexedTraversal Int ByteString Char-chars = from packedChars .> traverseList+-- @+-- 'chars' = 'unpackedChars' '.' 'traverse'+-- @+--+-- >>> anyOf chars (== 'h') "hello"+-- True+chars :: IndexedTraversal' Int ByteString Char+chars = traversedStrictTree8 {-# INLINE chars #-}++pattern Bytes :: [Word8] -> ByteString+pattern Bytes b <- (view unpackedBytes -> b) where+  Bytes b = review unpackedBytes b++pattern Chars :: String -> ByteString+pattern Chars b <- (view unpackedChars -> b) where+  Chars b = review unpackedChars b
src/Data/Complex/Lens.hs view
@@ -1,67 +1,148 @@ {-# LANGUAGE CPP #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE ViewPatterns #-}+{-# LANGUAGE PatternSynonyms #-}+ ----------------------------------------------------------------------------- -- | -- Module      :  Data.Complex.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  experimental--- Portability :  Rank2Types+-- Portability :  non-portable --+-- Lenses and traversals for complex numbers+-- ---------------------------------------------------------------------------- module Data.Complex.Lens-  ( real, imaginary, polarize-  , traverseComplex+  ( _realPart+  , _imagPart+  , _polar+  , _magnitude+  , _phase+  , _conjugate+  -- * Pattern Synonyms+  , pattern Polar+  , pattern Real+  , pattern Imaginary+  , pattern Conjugate   ) where -import Control.Applicative+import Prelude ()+ import Control.Lens+import Control.Lens.Internal.Prelude import Data.Complex --- | Access the 'realPart' of a 'Complex' number+-- $setup+-- >>> import Control.Lens+-- >>> import Data.Complex+-- >>> import Debug.SimpleReflect+-- >>> let { a ≈ b = abs (a - b) < 1e-6; infix 4 ≈ }++-- | Access the 'realPart' of a 'Complex' number. ----- >>> (1.0 :+ 0.0)^.real--- 1.0+-- >>> (a :+ b)^._realPart+-- a ----- @'real' :: 'Functor' f => (a -> f a) -> 'Complex' a -> f ('Complex' a)@-#if MIN_VERSION_base(4,4,0)-real :: Simple Lens (Complex a) a-#else-real :: RealFloat a => Simple Lens (Complex a) a-#endif-real f (a :+ b) = (:+ b) <$> f a+-- >>> a :+ b & _realPart *~ 2+-- a * 2 :+ b+--+-- @'_realPart' :: 'Functor' f => (a -> f a) -> 'Complex' a -> f ('Complex' a)@+_realPart :: Lens' (Complex a) a+_realPart f (a :+ b) = (:+ b) <$> f a+{-# INLINE _realPart #-} --- | Access the 'imaginaryPart' of a 'Complex' number+-- | Access the 'imagPart' of a 'Complex' number. ----- >>> (0.0 :+ 1.0)^.imaginary--- 1.0+-- >>> (a :+ b)^._imagPart+-- b ----- @'imaginary' :: 'Functor' f => (a -> f a) -> 'Complex' a -> f ('Complex' a)@-#if MIN_VERSION_base(4,4,0)-imaginary :: Simple Lens (Complex a) a-#else-imaginary :: RealFloat a => Simple Lens (Complex a) a-#endif-imaginary f (a :+ b) = (a :+) <$> f b+-- >>> a :+ b & _imagPart *~ 2+-- a :+ b * 2+--+-- @'_imagPart' :: 'Functor' f => (a -> f a) -> 'Complex' a -> f ('Complex' a)@+_imagPart :: Lens' (Complex a) a+_imagPart f (a :+ b) = (a :+) <$> f b+{-# INLINE _imagPart #-} --- | This isn't /quite/ a legal lens. Notably the +-- | This isn't /quite/ a legal t'Lens'. Notably the -- -- @'view' l ('set' l b a) = b@ ----- law is violated when you set a 'polar' value with 0 'magnitude' and non-zero 'phase'--- as the 'phase' information is lost. So don't do that!+-- law is violated when you set a 'polar' value with 0 'magnitude' and non-zero+-- 'phase' as the 'phase' information is lost, or with a negative 'magnitude'+-- which flips the 'phase' and retains a positive 'magnitude'. So don't do+-- that! ----- Otherwise, this is a perfectly cromulent 'Lens'.-polarize :: (RealFloat a, RealFloat b) => Iso (Complex a) (Complex b) (a,a) (b,b)-polarize = isos polar (uncurry mkPolar)-                polar (uncurry mkPolar)+-- Otherwise, this is a perfectly cromulent t'Lens'.+_polar :: RealFloat a => Iso' (Complex a) (a,a)+_polar = iso polar (uncurry mkPolar)+{-# INLINE _polar #-} --- | Traverse both the real and imaginary parts of a 'Complex' number.+pattern Polar :: RealFloat a => a -> a -> Complex a+pattern Polar m theta <- (view _polar -> (m, theta)) where+  Polar m theta = review _polar (m, theta)++pattern Real :: (Eq a, Num a) => a -> Complex a+pattern Real r      = r :+ 0++pattern Imaginary :: (Eq a, Num a) => a -> Complex a+pattern Imaginary i = 0 :+ i++-- | Access the 'magnitude' of a 'Complex' number. ----- > traverseComplex :: Applicative f => (a -> f b) -> Complex a -> f (Complex b)-#if MIN_VERSION_base(4,4,0)-traverseComplex :: Traversal (Complex a) (Complex b) a b-#else-traverseComplex :: (RealFloat a, RealFloat b) => Traversal (Complex a) (Complex b) a b-#endif-traverseComplex f (a :+ b) = (:+) <$> f a <*> f b+-- >>> (10.0 :+ 20.0) & _magnitude *~ 2+-- 20.0 :+ 40.0+--+-- This isn't /quite/ a legal t'Lens'. Notably the+--+-- @'view' l ('set' l b a) = b@+--+-- law is violated when you set a negative 'magnitude'. This flips the 'phase'+-- and retains a positive 'magnitude'. So don't do that!+--+-- Otherwise, this is a perfectly cromulent t'Lens'.+--+-- Setting the 'magnitude' of a zero 'Complex' number assumes the 'phase' is 0.+_magnitude :: RealFloat a => Lens' (Complex a) a+_magnitude f c = setMag <$> f r+  where setMag r' | r /= 0    = c * (r' / r :+ 0)+                  | otherwise = r' :+ 0+        r = magnitude c+{-# INLINE _magnitude #-}++-- | Access the 'phase' of a 'Complex' number.+--+-- >>> (mkPolar 10 (2-pi) & _phase +~ pi & view _phase) ≈ 2+-- True+--+-- This isn't /quite/ a legal t'Lens'. Notably the+--+-- @'view' l ('set' l b a) = b@+--+-- law is violated when you set a 'phase' outside the range @(-'pi', 'pi']@.+-- The phase is always in that range when queried. So don't do that!+--+-- Otherwise, this is a perfectly cromulent t'Lens'.+_phase :: RealFloat a => Lens' (Complex a) a+_phase f c = setPhase <$> f theta+  where setPhase theta' = c * cis (theta' - theta)+        theta = phase c+{-# INLINE _phase #-}++-- | Access the 'conjugate' of a 'Complex' number.+--+-- >>> (2.0 :+ 3.0) & _conjugate . _imagPart -~ 1+-- 2.0 :+ 4.0+--+-- >>> (mkPolar 10.0 2.0 ^. _conjugate . _phase) ≈ (-2.0)+-- True+_conjugate :: RealFloat a => Iso' (Complex a) (Complex a)+_conjugate = involuted conjugate+{-# INLINE _conjugate #-}++pattern Conjugate :: Num a => Complex a -> Complex a+pattern Conjugate a <- (conjugate -> a) where+  Conjugate a = conjugate a
src/Data/Data/Lens.hs view
@@ -3,15 +3,19 @@ {-# LANGUAGE Rank2Types #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE PatternGuards #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ExistentialQuantification #-}-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 704+{-# LANGUAGE GADTs #-}+#ifdef TRUSTWORTHY {-# LANGUAGE Trustworthy #-} #endif+{-# OPTIONS_GHC -fno-full-laziness #-} ----------------------------------------------------------------------------- -- | -- Module      :  Data.Data.Lens--- Copyright   :  (C) 2012 Edward Kmett, (C) 2006-2012 Neil Mitchell+-- Copyright   :  (C) 2012-2016 Edward Kmett, (C) 2006-2012 Neil Mitchell -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  experimental@@ -24,19 +28,32 @@ -- ---------------------------------------------------------------------------- module Data.Data.Lens-  ( template+  (+  -- * Generic Traversal+    template   , tinplate   , uniplate   , biplate-  -- * Traversal of Data+  -- * Field Accessor Traversal+  , upon+  , upon'+  , onceUpon+  , onceUpon'+  -- * Data Traversal   , gtraverse   ) where  import           Control.Applicative-import           Control.Arrow ((&&&)) import           Control.Exception as E-import           Control.Lens+import           Control.Lens.Internal.Context+import           Control.Lens.Internal.Indexed+import           Control.Lens.Lens+import           Control.Lens.Setter+import           Control.Lens.Traversal+import           Control.Lens.Type import           Data.Data+import           GHC.IO+import           Data.Maybe import           Data.Foldable import qualified Data.HashMap.Strict as M import           Data.HashMap.Strict (HashMap, (!))@@ -44,10 +61,19 @@ import           Data.HashSet (HashSet) import           Data.IORef import           Data.Monoid-import           GHC.IO import           GHC.Exts (realWorld#)-import           Unsafe.Coerce as Unsafe+import           Prelude +import qualified Data.Proxy as X (Proxy (..))+import qualified Data.Typeable as X (typeRep, eqT)+import qualified Data.Type.Equality as X++-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import Control.Lens.Internal.Doctest+-- >>> import Prelude hiding (head, tail)+ ------------------------------------------------------------------------------- -- Generic Traversal -------------------------------------------------------------------------------@@ -59,6 +85,7 @@ -- This really belongs in @Data.Data@. gtraverse :: (Applicative f, Data a) => (forall d. Data d => d -> f d) -> a -> f a gtraverse f = gfoldl (\x y -> x <*> f y) pure+{-# INLINE gtraverse #-}  ------------------------------------------------------------------------------- -- Naïve Traversal@@ -67,48 +94,171 @@ -- | Naïve 'Traversal' using 'Data'. This does not attempt to optimize the traversal. -- -- This is primarily useful when the children are immediately obvious, and for benchmarking.------ @--- 'tinplate' :: ('Data' a, 'Typeable' b) => 'Simple' 'Traversal' a b--- @-tinplate :: (Data a, Typeable b) => Simple Traversal a b+tinplate :: (Data s, Typeable a) => Traversal' s a tinplate f = gfoldl (step f) pure {-# INLINE tinplate #-} -step :: (Applicative f, Typeable b, Data d) => (b -> f b) -> f (d -> e) -> d -> f e-step f w d = w <*> case cast d of-  Just b  -> unsafeCoerce <$> f b-  Nothing -> tinplate f d+step :: forall s a f r. (Applicative f, Typeable a, Data s) => (a -> f a) -> f (s -> r) -> s -> f r+step f w s = w <*> case X.eqT :: Maybe (s X.:~: a) of+  Just X.Refl -> f s+  Nothing   -> tinplate f s {-# INLINE step #-}  ------------------------------------------------------------------------------- -- Smart Traversal ------------------------------------------------------------------------------- --- | Find every occurence of a given type @b@ recursively that doesn't require--- passing through something of type @b@ using 'Data', while avoiding traversal--- of areas that cannot contain a value of type @b@.+-- | Find every occurrence of a given type @a@ recursively that doesn't require+-- passing through something of type @a@ using 'Data', while avoiding traversal+-- of areas that cannot contain a value of type @a@. -- -- This is 'uniplate' with a more liberal signature.-template :: forall a b. (Data a, Typeable b) => Simple Traversal a b+template :: forall s a. (Data s, Typeable a) => Traversal' s a template = uniplateData (fromOracle answer) where-  answer = hitTest (undefined :: a) (undefined :: b)+  answer = hitTest (undefined :: s) (undefined :: a) {-# INLINE template #-}  -- | Find descendants of type @a@ non-transitively, while avoiding computation of areas that cannot contain values of -- type @a@ using 'Data'. ----- 'uniplate' is a useful default definition for 'Control.Plated.plate'-uniplate :: Data a => Simple Traversal a a+-- 'uniplate' is a useful default definition for 'Control.Lens.Plated.plate'+uniplate :: Data a => Traversal' a a uniplate = template {-# INLINE uniplate #-} --- | 'biplate' performs like 'template', except when @a ~ b@, it returns itself and nothing else.-biplate :: forall a b. (Data a, Typeable b) => Simple Traversal a b+-- | 'biplate' performs like 'template', except when @s ~ a@, it returns itself and nothing else.+biplate :: forall s a. (Data s, Typeable a) => Traversal' s a biplate = biplateData (fromOracle answer) where-  answer = hitTest (undefined :: a) (undefined :: b)+  answer = hitTest (undefined :: s) (undefined :: a) {-# INLINE biplate #-} +------------------------------------------------------------------------------+-- Automatic Traversal construction from field accessors+------------------------------------------------------------------------------++data FieldException a = FieldException !Int a++instance Show (FieldException a) where+  showsPrec d (FieldException i _) = showParen (d > 10) $+    showString "<field " . showsPrec 11 i . showChar '>'++instance Typeable a => Exception (FieldException a)++lookupon :: Typeable a => LensLike' (Indexing Identity) s a -> (s -> a) -> s -> Maybe (Int, Context a a s)+lookupon l field s = case unsafePerformIO $ E.try $ evaluate $ field $ s & indexing l %@~ \i (a::a) -> E.throw (FieldException i a) of+  Right _ -> Nothing+  Left e -> case fromException e of+    Nothing -> Nothing+    Just (FieldException i a) -> Just (i, Context (\a' -> set (elementOf l i) a' s) a)+{-# INLINE lookupon #-}+++-- | This automatically constructs a 'Traversal'' from an function.+--+-- >>> (2,4) & upon fst *~ 5+-- (10,4)+--+-- There are however, caveats on how this function can be used!+--+-- First, the user supplied function must access only one field of the specified type. That is to say the target+-- must be a single element that would be visited by @'holesOnOf' 'template' 'uniplate'@+--+-- Note: this even permits a number of functions to be used directly.+--+-- >>> [1,2,3,4] & upon head .~ 0+-- [0,2,3,4]+--+-- >>> [1,2,3,4] & upon last .~ 5+-- [1,2,3,5]+--+-- >>> [1,2,3,4] ^? upon tail+-- Just [2,3,4]+--+-- >>> "" ^? upon tail+-- Nothing+--+-- Accessing parents on the way down to children is okay:+--+-- >>> [1,2,3,4] & upon (tail.tail) .~ [10,20]+-- [1,2,10,20]+--+-- Second, the structure must not contain strict or unboxed fields of the same type that will be visited by 'Data'+--+-- @'upon' :: ('Data' s, 'Data' a) => (s -> a) -> 'IndexedTraversal'' [Int] s a@+upon :: forall p f s a. (Indexable [Int] p, Applicative f, Data s, Data a) => (s -> a) -> p a (f a) -> s -> f s+upon field f s = case lookupon template field s of+  Nothing -> pure s+  Just (i, Context k0 a0) ->+    let+      go :: [Int] -> Traversal' s a -> (a -> s) -> a -> f s+      go is l k a = case lookupon (l.uniplate) field s of+        Nothing                 -> k <$> indexed f (reverse is) a+        Just (j, Context k' a') -> go (j:is) (l.elementOf uniplate j) k' a'+    in go [i] (elementOf template i) k0 a0+{-# INLINE upon #-}++-- | The design of 'onceUpon'' doesn't allow it to search inside of values of type 'a' for other values of type 'a'.+-- 'upon'' provides this additional recursion.+--+-- Like 'onceUpon'', 'upon'' trusts the user supplied function more than 'upon' using it directly+-- as the accessor. This enables reading from the resulting 'Lens' to be considerably faster at the risk of+-- generating an illegal lens.+--+-- >>> upon' (tail.tail) .~ [10,20] $ [1,2,3,4]+-- [1,2,10,20]+upon' :: forall s a. (Data s, Data a) => (s -> a) -> IndexedLens' [Int] s a+upon' field f s = let+    ~(isn, kn) = case lookupon template field s of+      Nothing -> (error "upon': no index, not a member", const s)+      Just (i, Context k0 _) -> go [i] (elementOf template i) k0+    go :: [Int] -> Traversal' s a -> (a -> s) -> ([Int], a -> s)+    go is l k = case lookupon (l.uniplate) field s of+      Nothing                -> (reverse is, k)+      Just (j, Context k' _) -> go (j:is) (l.elementOf uniplate j) k'+  in kn <$> indexed f isn (field s)+{-# INLINE upon' #-}++-- | This automatically constructs a 'Traversal'' from a field accessor.+--+-- The index of the 'Traversal' can be used as an offset into @'elementOf' ('indexing' 'template')@ or into the list+-- returned by @'holesOf' 'template'@.+--+-- The design of 'onceUpon' doesn't allow it to search inside of values of type 'a' for other values of type 'a'.+-- 'upon' provides this additional recursion, but at the expense of performance.+--+-- >>> onceUpon (tail.tail) .~ [10,20] $ [1,2,3,4] -- BAD+-- [1,10,20]+--+-- >>> upon (tail.tail) .~ [10,20] $ [1,2,3,4] -- GOOD+-- [1,2,10,20]+--+-- When in doubt, use 'upon' instead.+onceUpon :: forall s a. (Data s, Typeable a) => (s -> a) -> IndexedTraversal' Int s a+onceUpon field f s = case lookupon template field s of+  Nothing               -> pure s+  Just (i, Context k a) -> k <$> indexed f i a+{-# INLINE onceUpon #-}++-- | This more trusting version of 'upon' uses your function directly as the getter for a 'Lens'.+--+-- This means that reading from 'upon'' is considerably faster than 'upon'.+--+-- However, you pay for faster access in two ways:+--+-- 1. When passed an illegal field accessor, 'upon'' will give you a 'Lens' that quietly violates+--    the laws, unlike 'upon', which will give you a legal 'Traversal' that avoids modifying the target.+--+-- 2. Modifying with the lens is slightly slower, since it has to go back and calculate the index after the fact.+--+-- When given a legal field accessor, the index of the 'Lens' can be used as an offset into+-- @'elementOf' ('indexed' 'template')@ or into the list returned by @'holesOf' 'template'@.+--+-- When in doubt, use 'upon'' instead.+onceUpon' :: forall s a. (Data s, Typeable a) => (s -> a) -> IndexedLens' Int s a+onceUpon' field f s = k <$> indexed f i (field s) where+  ~(i, Context k _) = fromMaybe (error "upon': no index, not a member") (lookupon template field s)+{-# INLINE onceUpon' #-}+ ------------------------------------------------------------------------------- -- Data Box -------------------------------------------------------------------------------@@ -119,7 +269,7 @@   }  dataBox :: Data a => a -> DataBox-dataBox a = DataBox (typeOf a) a+dataBox a = DataBox (X.typeRep [a]) a {-# INLINE dataBox #-}  -- partial, caught elsewhere@@ -130,6 +280,7 @@     gmapQ dataBox (fromConstr c `asTypeOf` x)   | otherwise = []   where dt = dataTypeOf x+{-# INLINE sybChildren #-}  ------------------------------------------------------------------------------- -- HitMap@@ -142,8 +293,8 @@   [ (tRational, S.singleton tInteger)   , (tInteger,  S.empty)   ] where-  tRational = typeOf (undefined :: Rational)-  tInteger  = typeOf (undefined :: Integer )+  tRational = X.typeRep (X.Proxy :: X.Proxy Rational)+  tInteger  = X.typeRep (X.Proxy :: X.Proxy Integer )  insertHitMap :: DataBox -> HitMap -> HitMap insertHitMap box hit = fixEq trans (populate box) `mappend` hit where@@ -158,7 +309,7 @@   trans :: HitMap -> HitMap   trans m = M.map f m where     f x = x `mappend` foldMap g x-    g x = M.lookupDefault (hit ! x) x m+    g x = fromMaybe (hit ! x) (M.lookup x m)  fixEq :: Eq a => (a -> a) -> a -> a fixEq f = go where@@ -209,63 +360,51 @@ -- Answers ------------------------------------------------------------------------------- -data Answer a-  = Hit a+data Answer b a+  = b ~ a => Hit a   | Follow   | Miss-  deriving (Eq,Ord,Show,Read) -instance Functor Answer where-  fmap f (Hit a) = Hit (f a)-  fmap _ Follow  = Follow-  fmap _ Miss    = Miss- ------------------------------------------------------------------------------- -- Oracles ------------------------------------------------------------------------------- -newtype Oracle a = Oracle { fromOracle :: forall t. Typeable t => t -> Answer a }--instance Functor Oracle where-  fmap f (Oracle g) = Oracle (fmap f . g)+newtype Oracle a = Oracle { fromOracle :: forall t. Typeable t => t -> Answer t a } -hitTest :: (Data a, Typeable b) => a -> b -> Oracle b-hitTest a b-  | kb <- typeOf b = case readCacheFollower (dataBox a) kb of-    Nothing -> Oracle $ \c ->-      if typeOf c == kb-      then Hit (unsafeCoerce c)-      else Follow-    Just p -> Oracle $ \c -> let kc = typeOf c in-      if kc == kb then Hit (unsafeCoerce c)-      else if p kc then Follow-      else Miss+hitTest :: forall a b. (Data a, Typeable b) => a -> b -> Oracle b+hitTest a b = Oracle $ \(c :: c) ->+  case X.eqT :: Maybe (c X.:~: b) of+    Just X.Refl -> Hit c+    Nothing ->+      case readCacheFollower (dataBox a) (typeOf b) of+        Just p | not (p (typeOf c)) -> Miss+        _ -> Follow  ------------------------------------------------------------------------------- -- Traversals -------------------------------------------------------------------------------  -biplateData :: forall f a b. (Applicative f, Data a, Typeable b) => (forall c. Typeable c => c -> Answer b) -> (b -> f b) -> a -> f a-biplateData o f a0 = go2 a0 where+biplateData :: forall f s a. (Applicative f, Data s) => (forall c. Typeable c => c -> Answer c a) -> (a -> f a) -> s -> f s+biplateData o f = go2 where   go :: Data d => d -> f d-  go a = gfoldl (\x y -> x <*> go2 y) pure a+  go = gfoldl (\x y -> x <*> go2 y) pure   go2 :: Data d => d -> f d-  go2 a = case o a of-    Hit b  -> Unsafe.unsafeCoerce <$> f b-    Follow -> go a-    Miss   -> pure a+  go2 s = case o s of+    Hit a  -> f a+    Follow -> go s+    Miss   -> pure s {-# INLINE biplateData #-} -uniplateData :: forall f a b. (Applicative f, Data a, Typeable b) => (forall c. Typeable c => c -> Answer b) -> (b -> f b) -> a -> f a-uniplateData o f a0 = go a0 where+uniplateData :: forall f s a. (Applicative f, Data s) => (forall c. Typeable c => c -> Answer c a) -> (a -> f a) -> s -> f s+uniplateData o f = go where   go :: Data d => d -> f d-  go a = gfoldl (\x y -> x <*> go2 y) pure a+  go = gfoldl (\x y -> x <*> go2 y) pure   go2 :: Data d => d -> f d-  go2 a = case o a of-    Hit b  -> Unsafe.unsafeCoerce <$> f b-    Follow -> go a-    Miss   -> pure a+  go2 s = case o s of+    Hit a  -> f a+    Follow -> go s+    Miss   -> pure s {-# INLINE uniplateData #-}  -------------------------------------------------------------------------------@@ -273,7 +412,7 @@ -------------------------------------------------------------------------------  part :: (a -> Bool) -> HashSet a -> (HashSet a, HashSet a)-part p = S.filter p &&& S.filter (not . p)+part p s = (S.filter p s, S.filter (not . p) s) {-# INLINE part #-}  type Follower = TypeRep -> Bool@@ -282,7 +421,6 @@ follower a b m   | S.null hit               = const False   | S.null miss              = const True-  | S.size hit < S.size miss = \k -> S.member k hit+  | S.size hit < S.size miss = S.member ?? hit   | otherwise = \k -> not (S.member k miss)   where (hit, miss) = part (\x -> S.member b (m ! x)) (S.insert a (m ! a))-
src/Data/Dynamic/Lens.hs view
@@ -1,27 +1,49 @@ {-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-} ----------------------------------------------------------------------------- -- | -- Module      :  Data.Dynamic.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-2016 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  portable+-- Stability   :  experimental+-- Portability :  non-portable -- ---------------------------------------------------------------------------- module Data.Dynamic.Lens-  ( dynamic+  ( AsDynamic(..)+  , pattern Data.Dynamic.Lens.Dynamic   ) where +import Control.Exception+import Control.Exception.Lens import Control.Lens import Data.Dynamic --- |--- Traverse the typed value contained in a 'Dynamic' where the type required by your function matches that--- of the contents of the 'Dynamic'.------ >>> ()^.by dynamic--- <<()>>-dynamic :: (Typeable a, Typeable b) => Projection Dynamic Dynamic a b-dynamic = projection toDyn fromDynamic-{-# INLINE dynamic #-}+-- | Any t'Dynamic' can be thrown as an t'Exception'+class AsDynamic t where+  -- | This t'Prism' allows you to traverse the typed value contained in a+  -- t'Dynamic' where the type required by your function matches that+  -- of the contents of the t'Dynamic', or construct a t'Dynamic' value+  -- out of whole cloth. It can also be used to catch or throw a t'Dynamic'+  -- value as 'SomeException'.+  --+  -- @+  -- '_Dynamic' :: 'Typeable' a => 'Prism'' t'Dynamic'      a+  -- '_Dynamic' :: 'Typeable' a => 'Prism'' 'SomeException' a+  -- @+  _Dynamic :: Typeable a => Prism' t a++instance AsDynamic Dynamic where+  _Dynamic = prism' toDyn fromDynamic+  {-# INLINE _Dynamic #-}++instance AsDynamic SomeException where+  _Dynamic = exception.prism' toDyn fromDynamic+  {-# INLINE _Dynamic #-}++pattern Dynamic :: (AsDynamic s, Typeable a) => a -> s+pattern Dynamic a <- (preview _Dynamic -> Just a) where+  Dynamic a = review _Dynamic a
src/Data/HashSet/Lens.hs view
@@ -2,7 +2,7 @@ ----------------------------------------------------------------------------- -- | -- Module      :  Data.HashSet.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional@@ -12,41 +12,44 @@ module Data.HashSet.Lens   ( setmapped   , setOf+  , hashMap   ) where -import Control.Lens.Getter-import Control.Lens.Internal-import Control.Lens.Setter-import Data.HashSet as HashSet+import Control.Lens.Getter (Getting, views)+import Control.Lens.Iso (iso)+import Control.Lens.Setter (setting)+import Control.Lens.Type+import qualified Data.HashSet as HashSet+import Data.HashSet (HashSet, fromMap, toMap)+import Data.HashMap.Lazy (HashMap) import Data.Hashable  -- $setup--- >>> :m + Data.HashSet Control.Lens+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens  -- | This 'Setter' can be used to change the type of a 'HashSet' by mapping -- the elements to new values. ----- Sadly, you can't create a valid 'Control.Lens.Traversal.Traversal' for a 'Set', but you can--- manipulate it by reading using 'folded' and reindexing it via 'setmap'.------ >>> over setmapped (+1) (fromList [1,2,3,4])--- fromList [2,3,4,5]-setmapped :: (Eq i, Hashable i, Eq j, Hashable j) => Setter (HashSet i) (HashSet j) i j-setmapped = sets HashSet.map+-- Sadly, you can't create a valid 'Traversal' for a 'Set', but you can+-- manipulate it by reading using 'Control.Lens.Fold.folded' and reindexing it via 'setmapped'.+setmapped :: (Eq j, Hashable j) => IndexPreservingSetter (HashSet i) (HashSet j) i j+setmapped = setting HashSet.map {-# INLINE setmapped #-} --- | Construct a set from a 'Getter', 'Control.Lens.Fold.Fold', 'Control.Lens.Traversal.Traversal', 'Control.Lens.Type.Lens' or 'Control.Lens.Iso.Iso'.------ >>> setOf (folded._2) [("hello",1),("world",2),("!!!",3)]--- fromList [1,2,3]+-- | Construct a set from a 'Getter', 'Control.Lens.Fold.Fold', 'Control.Lens.Traversal.Traversal', 'Control.Lens.Lens.Lens' or 'Control.Lens.Iso.Iso'. -- -- @--- 'setOf' :: 'Hashable' c         => 'Getter' a c           -> a -> 'HashSet' c--- 'setOf' :: ('Eq' c, 'Hashable' c) => 'Control.Lens.Fold.Fold' a c             -> a -> 'HashSet' c--- 'setOf' :: 'Hashable' c         => 'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a c       -> a -> 'HashSet' c--- 'setOf' :: 'Hashable' c         => 'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a c      -> a -> 'HashSet' c--- 'setOf' :: ('Eq' c, 'Hashable' c) => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> 'HashSet' c+-- 'setOf' :: 'Hashable' a         => 'Getter' s a     -> s -> 'HashSet' a+-- 'setOf' :: ('Eq' a, 'Hashable' a) => 'Fold' s a       -> s -> 'HashSet' a+-- 'setOf' :: 'Hashable' a         => 'Iso'' s a       -> s -> 'HashSet' a+-- 'setOf' :: 'Hashable' a         => 'Lens'' s a      -> s -> 'HashSet' a+-- 'setOf' :: ('Eq' a, 'Hashable' a) => 'Traversal'' s a -> s -> 'HashSet' a -- @-setOf :: Hashable c => Getting (HashSet c) a b c d -> a -> HashSet c-setOf l = runAccessor . l (Accessor . HashSet.singleton)+setOf :: Hashable a => Getting (HashSet a) s a -> s -> HashSet a+setOf l = views l HashSet.singleton {-# INLINE setOf #-}++-- | An `Iso` between a `HashSet` and a `HashMap` with unit values. \(\mathcal{O}(1)\).+hashMap :: Iso' (HashSet a) (HashMap a ())+hashMap = iso toMap fromMap
src/Data/IntSet/Lens.hs view
@@ -2,7 +2,7 @@ ----------------------------------------------------------------------------- -- | -- Module      :  Data.IntSet.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional@@ -16,13 +16,15 @@   ) where  import Control.Lens-import Control.Lens.Internal-import Data.IntSet as IntSet+import qualified Data.IntSet as IntSet+import Data.IntSet (IntSet)  -- $setup--- >>> :m + Data.IntSet.Lens Control.Lens+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import qualified Data.IntSet as IntSet --- | IntSet isn't Foldable, but this 'Fold' can be used to access the members of an 'IntSet'.+-- | IntSet isn't Foldable, but this t'Fold' can be used to access the members of an 'IntSet'. -- -- >>> sumOf members $ setOf folded [1,2,3,4] -- 10@@ -30,31 +32,34 @@ members = folding IntSet.toAscList {-# INLINE members #-} --- | This 'Setter' can be used to change the contents of an 'IntSet' by mapping+-- | This t'Setter' can be used to change the contents of an 'IntSet' by mapping -- the elements to new values. ----- Sadly, you can't create a valid 'Traversal' for a 'Set', because the number of+-- Sadly, you can't create a valid t'Traversal' for an 'IntSet', because the number of -- elements might change but you can manipulate it by reading using 'folded' and -- reindexing it via 'setmapped'. ----- >>> over setmapped (+1) (fromList [1,2,3,4])+-- >>> over setmapped (+1) (IntSet.fromList [1,2,3,4]) -- fromList [2,3,4,5]-setmapped :: Simple Setter IntSet Int-setmapped = sets IntSet.map+setmapped :: IndexPreservingSetter' IntSet Int+setmapped = setting IntSet.map {-# INLINE setmapped #-} --- | Construct an 'IntSet' from a 'Getter', 'Fold', 'Traversal', 'Lens' or 'Iso'.+-- | Construct an 'IntSet' from a t'Getter', t'Fold', t'Traversal', t'Lens' or t'Iso'. --+-- >>> setOf folded [1,2,3,4]+-- fromList [1,2,3,4]+-- -- >>> setOf (folded._2) [("hello",1),("world",2),("!!!",3)] -- fromList [1,2,3] -- -- @--- 'setOf' :: 'Getter' a 'Int'           -> a -> 'IntSet'--- 'setOf' :: 'Fold' a 'Int'             -> a -> 'IntSet'--- 'setOf' :: 'Simple' 'Iso' a 'Int'       -> a -> 'IntSet'--- 'setOf' :: 'Simple' 'Lens' a 'Int'      -> a -> 'IntSet'--- 'setOf' :: 'Simple' 'Traversal' a 'Int' -> a -> 'IntSet'+-- 'setOf' :: t'Getter' s 'Int'     -> s -> 'IntSet'+-- 'setOf' :: t'Fold' s 'Int'       -> s -> 'IntSet'+-- 'setOf' :: t'Iso'' s 'Int'       -> s -> 'IntSet'+-- 'setOf' :: t'Lens'' s 'Int'      -> s -> 'IntSet'+-- 'setOf' :: t'Traversal'' s 'Int' -> s -> 'IntSet' -- @-setOf :: Getting IntSet a b Int d -> a -> IntSet-setOf l = runAccessor . l (Accessor . IntSet.singleton)+setOf :: Getting IntSet s Int -> s -> IntSet+setOf l = views l IntSet.singleton {-# INLINE setOf #-}
src/Data/List/Lens.hs view
@@ -1,11 +1,7 @@-{-# LANGUAGE LiberalTypeSynonyms #-}-{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE BangPatterns #-}-{-# LANGUAGE Rank2Types #-} ----------------------------------------------------------------------------- -- | -- Module      :  Data.List.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional@@ -13,270 +9,105 @@ -- -- Traversals for manipulating parts of a list. --------------------------------------------------------------------------------module Data.List.Lens-  ( _head-  , _tail-  , _last-  , _init-  , interspersed-  , intercalated-  -- * Traversals-  , traverseList-  , traverseHead-  , traverseTail-  , traverseInit-  , traverseLast-  , (~:), (=:)-  , (<~:), (<=:)-  , (++~), (<++~)-  , (++=), (<++=)-  ) where--import Control.Applicative-import Control.Lens-import Control.Monad.State as State (MonadState, modify)-import Data.List--infixr 4 ++~, <++~-infixl 4 ~:, <~:-infix 4 =:, <=:, ++=, <++=---- | A lens reading and writing to the head of a /non-empty/ list.------ Attempting to read or write to the head of an /empty/ list will result in an 'error'.------ >>> [1,2,3]^._head--- 1-_head :: Simple Lens [a] a-_head _ [] = error "_head: empty list"-_head f (a:as) = (:as) <$> f a-{-# INLINE _head #-}---- | A lens reading and writing to the tail of a /non-empty/ list------ Attempting to read or write to the tail of an /empty/ list will result in an 'error'.------ >>> _tail .~ [3,4,5] $ [1,2]--- [1,3,4,5]-_tail :: Simple Lens [a] [a]-_tail _ [] = error "_tail: empty list"-_tail f (a:as) = (a:) <$> f as-{-# INLINE _tail #-}---- | A lens reading and writing to the last element of a /non-empty/ list------ Attempting to read or write to the last element of an /empty/ list will result in an 'error'.------ >>> [1,2]^._last--- 2-_last :: Simple Lens [a] a-_last _ []     = error "_last: empty list"-_last f [a]    = return <$> f a-_last f (a:as) = (a:) <$> _last f as-{-# INLINE _last #-}---- | A lens reading and replacing all but the a last element of a /non-empty/ list------ Attempting to read or write to all but the last element of an /empty/ list will result in an 'error'.------ >>> [1,2,3,4]^._init--- [1,2,3]-_init :: Simple Lens [a] [a]-_init _ [] = error "_init: empty list"-_init f as = (++ [Prelude.last as]) <$> f (Prelude.init as)-{-# INLINE _init #-}---- | Obtain a version of the list with the supplied value interspersed.------ >>> "abcde"^.interspersed ','--- "a,b,c,d,e"+-- Additional optics for manipulating lists are present more+-- generically in this package. ----- > xs^.interspersed a = intersperse a xs-interspersed :: a -> Getter [a] [a]-interspersed = to . intersperse-{-# INLINE interspersed #-}---- | Obtain a version of the list with the supplied value intercalated.-intercalated :: [a] -> Getter [[a]] [a]-intercalated = to . intercalate-{-# INLINE intercalated #-}---- | Indexed traversal of a list. The position in the list is available as the index.-traverseList :: IndexedTraversal Int [a] [b] a b-traverseList = index $ go (0::Int) where-  go !n f (x:xs) = (:) <$> f n x <*> go (n + 1) f xs-  go _ _ [] = pure []-{-# INLINE traverseList #-}---- | A traversal for reading and writing to the head of a list+-- The 'Control.Lens.At.Ixed' class allows traversing the element at a+-- specific list index. ----- The position of the head in the original list (0) is available as the index.+-- >>> [0..10] ^? ix 4+-- Just 4 ----- >>> traverseHead +~ 1 $ [1,2,3]--- [2,2,3]+-- >>> [0..5] & ix 4 .~ 2+-- [0,1,2,3,2,5] ----- @'traverseHead' :: 'Applicative' f => (a -> f a) -> [a] -> f [a]@-traverseHead :: SimpleIndexedTraversal Int [a] a-traverseHead = index $ \f aas -> case aas of-  []     -> pure []-  (a:as) -> (:as) <$> f (0::Int) a-{-# INLINE traverseHead #-}---- | A traversal for editing the tail of a list+-- >>> [0..10] ^? ix 14+-- Nothing ----- The position of each element /in the original list/ is available as the index.+-- >>> [0..5] & ix 14 .~ 2+-- [0,1,2,3,4,5] ----- >>> traverseTail +~ 1 $ [1,2,3]--- [1,3,4]+-- The 'Control.Lens.Cons.Cons' and 'Control.Lens.Empty.AsEmpty'+-- classes provide 'Control.Lens.Prism.Prism's for list constructors. ----- @'traverseTail' :: 'Applicative' f => (a -> f a) -> [a] -> f [a]@-traverseTail :: SimpleIndexedTraversal Int [a] a-traverseTail = index $ \f aas -> case aas of-  []     -> pure []-  (a:as) -> (a:) <$> withIndex traverseList (f . (+1)) as-{-# INLINE traverseTail #-}---- | A traversal the last element in a list+-- >>> [1..10] ^? _Cons+-- Just (1,[2,3,4,5,6,7,8,9,10]) ----- The position of the last element in the original list is available as the index.+-- >>> [] ^? _Cons+-- Nothing ----- >>> traverseLast +~ 1 $ [1,2,3]--- [1,2,4]+-- >>> [] ^? _Empty+-- Just () ----- @'traverseLast' :: 'Applicative' f => (a -> f a) -> [a] -> f [a]@-traverseLast :: SimpleIndexedTraversal Int [a] a-traverseLast = index $ \f xs0 -> let-    go [a]    n = return <$> f n a-    go (a:as) n = (a:) <$> (go as $! n + 1)-    go []     _ = pure []-  in go xs0 (0::Int) where-{-# INLINE traverseLast #-}---- | A traversal of all but the last element of a list+-- >>> _Cons # (1, _Empty # ()) :: [Int]+-- [1] ----- The position of each element is available as the index.+-- Additionally, 'Control.Lens.Cons.Snoc' provides a+-- 'Control.Lens.Prism.Prism' for accessing the end of a list. Note+-- that this 'Control.Lens.Prism.Prism' always will need to traverse+-- the whole list. ----- >>> traverseInit +~ 1 $ [1,2,3]--- [2,3,3]+-- >>> [1..5] ^? _Snoc+-- Just ([1,2,3,4],5) ----- @'traverseInit' :: 'Applicative' f => (a -> f a) -> [a] -> f [a]@-traverseInit :: SimpleIndexedTraversal Int [a] a-traverseInit = index $ \f aas -> case aas of-  [] -> pure []-  as -> (++ [Prelude.last as]) <$> withIndex traverseList f (Prelude.init as)-{-# INLINE traverseInit #-}---- | Cons onto the list(s) referenced by a 'Setter'.+-- >>> _Snoc # ([1,2],5)+-- [1,2,5] ----- >>> 'h' ~: _1 $ ("ello","world")--- ("hello","world")+-- An instance of 'Control.Lens.Plated.Plated' allows for finding+-- locations in the list where a traversal matches. ----- @--- ('~:') :: b -> 'Simple' 'Setter' a [b]    -> a -> a--- ('~:') :: b -> 'Simple' 'Traversal' a [b] -> a -> a--- ('~:') :: b -> 'Simple' 'Lens' a [b]      -> a -> a--- ('~:') :: b -> 'Simple' 'Iso' a [b]       -> a -> a--- @-(~:) :: c -> Setting a b [c] [c] -> a -> b-n ~: l = over l (n :)-{-# INLINE (~:) #-}---- | Cons onto the list(s) referenced by a 'Setter' in your monad state+-- >>> [Nothing, Just 7, Just 3, Nothing] & deep (ix 0 . _Just) +~ 10+-- [Nothing,Just 17,Just 3,Nothing] ----- @--- ('=:') :: 'MonadState' a m => c -> 'Simple' 'Setter' a [c]    -> m ()--- ('=:') :: 'MonadState' a m => c -> 'Simple' 'Traversal' a [c] -> m ()--- ('=:') :: 'MonadState' a m => c -> 'Simple' 'Lens' a [c]      -> m ()--- ('=:') :: 'MonadState' a m => c -> 'Simple' 'Iso' a [c]       -> m ()--- @-(=:) :: MonadState a m => c -> SimpleSetting a [c] -> m ()-n =: l = modify (n ~: l)-{-# INLINE (=:) #-}---- | Cons onto the list(s) referenced by a 'Lens' (or 'Traversal'), returning the result.+-- An instance of 'Control.Lens.Iso.Reversing' provides an+-- 'Control.Lens.Iso.Iso' between a list and its reverse. ----- If you use this with a 'Traversal' you will receive back the concatenation of all of--- the resulting lists instead of an individual result.+-- >>> "live" & reversed %~ ('d':)+-- "lived" ----- >>> 'h' <~: _1 $ ("ello","world")--- ("hello",("hello","world"))+-- It's possible to work under a prefix or suffix of a list using+-- 'Control.Lens.Prism.Prefixed' and 'Control.Lens.Prism.Suffixed'. ----- @--- ('<~:') :: b -> 'Simple' 'Lens' a [b]       -> a -> ([b], a)--- ('<~:') :: b -> 'Simple' 'Iso' a [b]        -> a -> ([b], a)--- ('<~:') :: b -> 'Simple' 'Traversal' a [b]  -> a -> ([b], a)--- @-(<~:) :: c -> LensLike ((,)[c]) a b [c] [c] -> a -> ([c], b)-n <~: l = l <%~ (n :)-{-# INLINE (<~:) #-}---- | Cons onto the list(s) referenced by a 'Lens' (or 'Traversal') into your monad state,--- returning the result.+-- >>> "preview" ^? prefixed "pre"+-- Just "view" ----- If you use this with a 'Traversal', you will receive back the concatenation of all--- of the resulting lists instead of an individual result.+-- >>> suffixed ".o" # "hello"+-- "hello.o" ----- @--- ('<=:') :: 'MonadState' a m => 'Simple' 'Lens' a [c]      -> c -> m [c]--- ('<=:') :: 'MonadState' a m => 'Simple' 'Iso' a [c]       -> c -> m [c]--- ('<=:') :: 'MonadState' a m => 'Simple' 'Traversal' a [c] -> c -> m [c]--- @-(<=:) :: MonadState a m => c -> SimpleLensLike ((,)[c]) a [c] -> m [c]-n <=: l = l <%= (n :)-{-# INLINE (<=:) #-}----- | Append to the target of a list-valued setter by appending to it with ('++').+-- At present, "Data.List.Lens" re-exports 'Prefixed' and 'Suffixed' for+-- backwards compatibility, as 'prefixed' and 'suffixed' used to be top-level+-- functions defined in this module. This may change in a future major release+-- of @lens@. ----- ('Data.Monoid.<>~') generalizes this operation to an arbitrary 'Monoid'.+-- Finally, it's possible to traverse, fold over, and map over+-- index-value pairs thanks to instances of+-- 'Control.Lens.Indexed.TraversableWithIndex',+-- 'Control.Lens.Indexed.FoldableWithIndex', and+-- 'Control.Lens.Indexed.FunctorWithIndex'. ----- >>> :m + Control.Lens--- >>> both ++~ "!!!" $ ("hello","world")--- ("hello!!!","world!!!")+-- >>> imap (,) "Hello"+-- [(0,'H'),(1,'e'),(2,'l'),(3,'l'),(4,'o')] ----- @--- ('++~') :: 'Simple' 'Setter' a [b] -> [b] -> a -> a--- ('++~') :: 'Simple' 'Iso' a [b] -> [b] -> a -> a--- ('++~') :: 'Simple' 'Lens' a [b] -> [b] -> a -> a--- ('++~') :: 'Simple' 'Traversal' a [b] -> [b] -> a -> a--- @-(++~) :: Setting a b [c] [c] -> [c] -> a -> b-l ++~ n = over l (++ n)-{-# INLINE (++~) #-}---- | Append to the target(s) of a 'Simple' 'Lens', 'Iso', 'Setter' or 'Traversal' with ('++') in the current state.+-- >>> ifoldMap replicate "Hello"+-- "ellllloooo" ----- ('Data.Monoid.<>=') generalizes this operation to an arbitrary 'Monoid'.+-- >>> itraverse_ (curry print) "Hello"+-- (0,'H')+-- (1,'e')+-- (2,'l')+-- (3,'l')+-- (4,'o') ----- @--- ('++=') :: 'MonadState' a m => 'Simple' 'Setter' a [b] -> [b] -> m ()--- ('++=') :: 'MonadState' a m => 'Simple' 'Iso' a [b] -> [b] -> m ()--- ('++=') :: 'MonadState' a m => 'Simple' 'Lens' a [b] -> [b] -> m ()--- ('++=') :: 'MonadState' a m => 'Simple' 'Traversal' a [b] -> [b] -> m ()--- @-(++=) :: MonadState a m => SimpleSetting a [b] -> [b] -> m ()-l ++= b = State.modify (l ++~ b)-{-# INLINE (++=) #-}+----------------------------------------------------------------------------+module Data.List.Lens+  ( Prefixed(..)+  , Suffixed(..)+  , stripSuffix+  ) where --- | Append onto the end of the list targeted by a 'Lens' and return the result.------ ('Data.Monoid.<<>~') generalizes this operation to an arbitrary 'Monoid'.------ When using a 'Traversal', the result returned is actually the concatenation of all of the results.------ When you do not need the result of the operation, ('++~') is more flexible.-(<++~) :: LensLike ((,)[c]) a b [c] [c] -> [c] -> a -> ([c], b)-l <++~ m = l <%~ (++ m)-{-# INLINE (<++~) #-}+import Control.Lens.Prism (Prefixed(..), Suffixed(..))+import Control.Lens.Internal.List (stripSuffix) --- | Append onto the end of the list targeted by a 'Lens' into the current monadic state, and return the result.------ ('Data.Monoid.<<>=') generalizes this operation to an arbitrary 'Monoid'.------ When using a 'Traversal', the result returned is actually the concatenation of all of the results.------ When you do not need the result of the operation, ('++=') is more flexible.-(<++=) :: MonadState a m => SimpleLensLike ((,)[b]) a [b] -> [b] -> m [b]-l <++= m = l <%= (++ m)-{-# INLINE (<++=) #-}+--- $setup+--- >>> :set -XNoOverloadedStrings+--- >>> import Control.Lens
+ src/Data/Map/Lens.hs view
@@ -0,0 +1,100 @@+-----------------------------------------------------------------------------+-- |+-- Copyright   :  (C) 2014-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-- One of most commonly-asked questions about this package is whether+-- it provides lenses for working with 'Data.Map.Map'. It does, but their uses+-- are perhaps obscured by their genericity. This module exists to provide+-- documentation for them.+--+-- 'Data.Map.Map' is an instance of 'Control.Lens.At.At', so we have a lenses+-- on values at keys:+--+-- >>> Map.fromList [(1, "world")] ^.at 1+-- Just "world"+--+-- >>> at 1 .~ Just "world" $ Map.empty+-- fromList [(1,"world")]+--+-- >>> at 0 ?~ "hello" $ Map.empty+-- fromList [(0,"hello")]+--+-- We can traverse, fold over, and map over key-value pairs in a+-- 'Data.Map.Map', thanks to its 'Control.Lens.Indexed.TraversableWithIndex',+-- 'Control.Lens.Indexed.FoldableWithIndex', and+-- 'Control.Lens.Indexed.FunctorWithIndex' instances.+--+-- >>> imap const $ Map.fromList [(1, "Venus")]+-- fromList [(1,1)]+--+-- >>> ifoldMap (\i _ -> Sum i) $ Map.fromList [(2, "Earth"), (3, "Mars")]+-- Sum {getSum = 5}+--+-- >>> itraverse_ (curry print) $ Map.fromList [(4, "Jupiter")]+-- (4,"Jupiter")+--+-- >>> itoList $ Map.fromList [(5, "Saturn")]+-- [(5,"Saturn")]+--+-- A related class, 'Control.Lens.At.Ixed', allows us to use+-- 'Control.Lens.At.ix' to traverse a value at a particular key.+--+-- >>> ix 2 %~ ("New " ++) $ Map.fromList [(2, "Earth")]+-- fromList [(2,"New Earth")]+--+-- >>> preview (ix 8) $ Map.empty+-- Nothing+--+-- Additionally, 'Data.Map.Map' has 'Control.Lens.Traversal.TraverseMin' and+-- 'Control.Lens.Traversal.TraverseMax' instances, which let us traverse over+-- the value at the least and greatest keys, respectively.+--+-- >>> preview traverseMin $ Map.fromList [(5, "Saturn"), (6, "Uranus")]+-- Just "Saturn"+--+-- >>> preview traverseMax $ Map.fromList [(5, "Saturn"), (6, "Uranus")]+-- Just "Uranus"+--+-----------------------------------------------------------------------------+module Data.Map.Lens+  ( toMapOf+  ) where++import Control.Lens.Getter ( IndexedGetting, iviews )+import qualified Data.Map as Map++-- $setup+-- >>> import Control.Lens+-- >>> import Data.Monoid+-- >>> import qualified Data.Map as Map+-- >>> :set -XNoOverloadedStrings++-- | Construct a map from a 'IndexedGetter', 'Control.Lens.Fold.IndexedFold', 'Control.Lens.Traversal.IndexedTraversal' or 'Control.Lens.Lens.IndexedLens'+--+-- The construction is left-biased (see 'Data.Map.Lazy.union'), i.e. the first+-- occurrences of keys in the fold or traversal order are preferred.+--+-- >>> toMapOf folded ["hello", "world"]+-- fromList [(0,"hello"),(1,"world")]+--+-- >>> toMapOf (folded . ifolded) [('a',"alpha"),('b', "beta")]+-- fromList [('a',"alpha"),('b',"beta")]+--+-- >>> toMapOf (folded <.> folded) ["foo", "bar"]+-- fromList [((0,0),'f'),((0,1),'o'),((0,2),'o'),((1,0),'b'),((1,1),'a'),((1,2),'r')]+--+-- >>> toMapOf ifolded $ Map.fromList [('a', "hello"), ('b', "world")]+-- fromList [('a',"hello"),('b',"world")]+--+-- @+-- 'toMapOf' ::          'IndexedGetter' i s a     -> s -> 'Map.Map' i a+-- 'toMapOf' :: 'Ord' i => 'IndexedFold' i s a       -> s -> 'Map.Map' i a+-- 'toMapOf' ::          'IndexedLens'' i s a      -> s -> 'Map.Map' i a+-- 'toMapOf' :: 'Ord' i => 'IndexedTraversal'' i s a -> s -> 'Map.Map' i a+-- @+toMapOf :: IndexedGetting i (Map.Map i a) s a -> s -> Map.Map i a+toMapOf l = iviews l Map.singleton
− src/Data/Monoid/Lens.hs
@@ -1,131 +0,0 @@--------------------------------------------------------------------------------- |--- Module      :  Data.Monoid.Lens--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  experimental--- Portability :  Rank2Types---------------------------------------------------------------------------------module Data.Monoid.Lens-  ( (<>~), (<<>~)-  , (<>=), (<<>=)-  , _dual, _endo, _all, _any, _sum, _product, _first, _last-  ) where--import Data.Monoid-import Control.Lens-import Control.Monad.State.Class as State--infixr 4 <>~, <<>~-infix 4 <>=, <<>=---- | Modify the target of a monoidally valued by 'mappend'ing another value.------ >>> :m + Control.Lens--- >>> both <>~ "!!!" $ ("hello","world")--- ("hello!!!","world!!!")------ @--- ('<>~') :: 'Monoid' c => 'Setter' a b c c -> c -> a -> b--- ('<>~') :: 'Monoid' c => 'Iso' a b c c -> c -> a -> b--- ('<>~') :: 'Monoid' c => 'Lens' a b c c -> c -> a -> b--- ('<>~') :: 'Monoid' c => 'Traversal' a b c c -> c -> a -> b--- @-(<>~) :: Monoid c => Setting a b c c -> c -> a -> b-l <>~ n = over l (`mappend` n)-{-# INLINE (<>~) #-}---- | Modify the target(s) of a 'Simple' 'Lens', 'Iso', 'Setter' or 'Traversal' by 'mappend'ing a value.------ @--- ('<>=') :: ('MonadState' a m, 'Monoid' b) => 'Simple' 'Setter' a b -> b -> m ()--- ('<>=') :: ('MonadState' a m, 'Monoid' b) => 'Simple' 'Iso' a b -> b -> m ()--- ('<>=') :: ('MonadState' a m, 'Monoid' b) => 'Simple' 'Lens' a b -> b -> m ()--- ('<>=') :: ('MonadState' a m, 'Monoid' b) => 'Simple' 'Traversal' a b -> b -> m ()--- @-(<>=) :: (MonadState a m, Monoid b) => SimpleSetting a b -> b -> m ()-l <>= b = State.modify (l <>~ b)-{-# INLINE (<>=) #-}----- | 'mappend' a monoidal value onto the end of the target of a 'Lens' and--- return the result------ When you do not need the result of the operation, ('<>~') is more flexible.-(<<>~) :: Monoid m => LensLike ((,)m) a b m m -> m -> a -> (m, b)-l <<>~ m = l <%~ (`mappend` m)-{-# INLINE (<<>~) #-}---- | 'mappend' a monoidal value onto the end of the target of a 'Lens' into--- your monad's state and return the result.------ When you do not need the result of the operation, ('<>=') is more flexible.-(<<>=) :: (MonadState a m, Monoid r) => SimpleLensLike ((,)r) a r -> r -> m r-l <<>= r = l <%= (`mappend` r)-{-# INLINE (<<>=) #-}---- | Isomorphism for 'Dual'-_dual :: Iso a b (Dual a) (Dual b)-_dual = isos Dual getDual Dual getDual-{-# INLINE _dual #-}---- | Isomorphism for 'Endo'-_endo :: Iso (a -> a) (b -> b) (Endo a) (Endo b)-_endo = isos Endo appEndo Endo appEndo-{-# INLINE _endo #-}---- | Isomorphism for 'All'------ >>> :m + Control.Lens Data.Monoid.Lens Data.Foldable--- >>> ala _all foldMap [True,True]--- True------ >>> :m + Control.Lens Data.Monoid.Lens Data.Foldable--- >>> ala _all foldMap [True,False]--- False-_all :: Simple Iso Bool All-_all = iso All getAll-{-# INLINE _all #-}---- | Isomorphism for 'Any'------ >>> :m + Control.Lens Data.Monoid.Lens Data.Foldable--- >>> ala _any foldMap [False,False]--- False------ >>> :m + Control.Lens Data.Monoid.Lens Data.Foldable--- >>> ala _any foldMap [True,False]--- True-_any :: Simple Iso Bool Any-_any = iso Any getAny-{-# INLINE _any #-}---- | Isomorphism for 'Sum'------ >>> :m + Control.Lens Data.Monoid.Lens Data.Foldable--- >>> ala _sum foldMap [1,2,3,4]--- 10-_sum :: Iso a b (Sum a) (Sum b)-_sum = isos Sum getSum Sum getSum-{-# INLINE _sum #-}---- | Isomorphism for 'Product'------ >>> :m + Control.Lens Data.Monoid.Lens Data.Foldable--- >>> ala _product foldMap [1,2,3,4]--- 24-_product :: Iso a b (Product a) (Product b)-_product = isos Product getProduct Product getProduct-{-# INLINE _product #-}---- | Isomorphism for 'First'-_first :: Iso (Maybe a) (Maybe b) (First a) (First b)-_first = isos First getFirst First getFirst-{-# INLINE _first #-}---- | Isomorphism for 'Last'-_last :: Iso (Maybe a) (Maybe b) (Last a) (Last b)-_last = isos Last getLast Last getLast-{-# INLINE _last #-}
src/Data/Sequence/Lens.hs view
@@ -1,103 +1,142 @@-{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE Rank2Types #-}+{-# LANGUAGE FlexibleContexts #-} ----------------------------------------------------------------------------- -- | -- Module      :  Data.Sequence.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  portable+-- Stability   :  experimental+-- Portability :  non-portable -- ---------------------------------------------------------------------------- module Data.Sequence.Lens-  ( ordinal, viewL, viewR-  , traverseHead, traverseTail-  , traverseLast, traverseInit-  , traverseTo, traverseFrom-  , traverseSlice+  ( viewL, viewR+  , sliced, slicedTo, slicedFrom+  , seqOf   ) where  import Control.Applicative-import Control.Lens as Lens+import Control.Lens import Data.Monoid-import Data.Sequence as Seq+import qualified Data.Sequence as Seq+import Data.Sequence (Seq, ViewL(EmptyL), ViewR(EmptyR), (><), viewl, viewr)+import Prelude --- | A 'Lens' that can access the @n@th element of a 'Seq'.------ Note: This is only a legal lens if there is already such an element!-ordinal :: Int -> SimpleIndexedLens Int (Seq a) a-ordinal i = Lens.index $ \ f m -> (\a -> update i a m) <$> f i (Seq.index m i)+-- $setup+-- >>> import Control.Lens+-- >>> import qualified Data.Sequence as Seq+-- >>> import Data.Sequence (ViewL(EmptyL), ViewR(EmptyR))+-- >>> import Debug.SimpleReflect.Expr+-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g)+-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f+-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g  -- * Sequence isomorphisms  -- | A 'Seq' is isomorphic to a 'ViewL' ----- @'viewl' m = m '^.' 'viewL'@+-- @'viewl' m ≡ m '^.' 'viewL'@+--+-- >>> Seq.fromList [a,b,c] ^. viewL+-- a :< fromList [b,c]+--+-- >>> Seq.empty ^. viewL+-- EmptyL+--+-- >>> EmptyL ^. from viewL+-- fromList []+--+-- >>> review viewL $ a Seq.:< Seq.fromList [b,c]+-- fromList [a,b,c] viewL :: Iso (Seq a) (Seq b) (ViewL a) (ViewL b)-viewL = isos viewl unviewl viewl unviewl where--unviewl :: ViewL a -> Seq a-unviewl EmptyL = mempty-unviewl (a :< as) = a <| as+viewL = iso viewl $ \ xs -> case xs of+  EmptyL ->  mempty+  a Seq.:< as -> a Seq.<| as {-# INLINE viewL #-}  -- | A 'Seq' is isomorphic to a 'ViewR' ----- @'viewr' m = m '^.' 'viewR'@+-- @'viewr' m ≡ m '^.' 'viewR'@+--+-- >>> Seq.fromList [a,b,c] ^. viewR+-- fromList [a,b] :> c+--+-- >>> Seq.empty ^. viewR+-- EmptyR+--+-- >>> EmptyR ^. from viewR+-- fromList []+--+-- >>> review viewR $ Seq.fromList [a,b] Seq.:> c+-- fromList [a,b,c] viewR :: Iso (Seq a) (Seq b) (ViewR a) (ViewR b)-viewR = isos viewr unviewr viewr unviewr where+viewR = iso viewr $ \xs -> case xs of+  EmptyR  -> mempty+  as Seq.:> a -> as Seq.|> a {-# INLINE viewR #-} -unviewr :: ViewR a -> Seq a-unviewr EmptyR = mempty-unviewr (as :> a) = as |> a---- * Traversals---- | Traverse the head of a 'Seq'-traverseHead :: SimpleIndexedTraversal Int (Seq a) a-traverseHead = Lens.index $ \f m -> case viewl m of-  a :< as -> (<| as) <$> f (0::Int) a-  EmptyL  -> pure m-{-# INLINE traverseHead #-}---- | Traverse the tail of a 'Seq'-traverseTail :: SimpleIndexedTraversal Int (Seq a) a-traverseTail = Lens.index $ \f m -> case viewl m of-  a :< as -> (a <|) <$> itraverse (f . (+1)) as-  EmptyL  -> pure m-{-# INLINE traverseTail #-}---- | Traverse the last element of a 'Seq'-traverseLast :: SimpleIndexedTraversal Int (Seq a) a-traverseLast = Lens.index $ \f m ->  case viewr m of-  as :> a -> (as |>) <$> f (Seq.length as) a-  EmptyR  -> pure m-{-# INLINE traverseLast #-}---- | Traverse all but the last element of a 'Seq'-traverseInit :: SimpleIndexedTraversal Int (Seq a) a-traverseInit = Lens.index $ \ f m -> case viewr m of-  as :> a -> (|> a) <$> itraverse f as-  EmptyR  -> pure m-{-# INLINE traverseInit #-}- -- | Traverse the first @n@ elements of a 'Seq'-traverseTo :: Int -> SimpleIndexedTraversal Int (Seq a) a-traverseTo n = Lens.index $ \f m -> case Seq.splitAt n m of-  (l,r) -> (>< r) <$> itraverse f l-{-# INLINE traverseTo #-}+--+-- >>> Seq.fromList [a,b,c,d,e] ^.. slicedTo 2+-- [a,b]+--+-- >>> Seq.fromList [a,b,c,d,e] & slicedTo 2 %~ f+-- fromList [f a,f b,c,d,e]+--+-- >>> Seq.fromList [a,b,c,d,e] & slicedTo 10 .~ x+-- fromList [x,x,x,x,x]+slicedTo :: Int -> IndexedTraversal' Int (Seq a) a+slicedTo n f m = case Seq.splitAt n m of+  (l,r) -> (>< r) <$> itraverse (indexed f) l+{-# INLINE slicedTo #-}  -- | Traverse all but the first @n@ elements of a 'Seq'-traverseFrom :: Int -> SimpleIndexedTraversal Int (Seq a) a-traverseFrom n = Lens.index $ \ f m -> case Seq.splitAt n m of-  (l,r) -> (l ><) <$> itraverse (f . (+n)) r-{-# INLINE traverseFrom #-}+--+-- >>> Seq.fromList [a,b,c,d,e] ^.. slicedFrom 2+-- [c,d,e]+--+-- >>> Seq.fromList [a,b,c,d,e] & slicedFrom 2 %~ f+-- fromList [a,b,f c,f d,f e]+--+-- >>> Seq.fromList [a,b,c,d,e] & slicedFrom 10 .~ x+-- fromList [a,b,c,d,e]+slicedFrom :: Int -> IndexedTraversal' Int (Seq a) a+slicedFrom n f m = case Seq.splitAt n m of+  (l,r) -> (l ><) <$> itraverse (indexed f . (+n)) r+{-# INLINE slicedFrom #-} --- | Travere all the elements numbered from @i@ to @j@ of a 'Seq'-traverseSlice :: Int -> Int -> SimpleIndexedTraversal Int (Seq a) a-traverseSlice i j = Lens.index $ \ f s -> case Seq.splitAt i s of+-- | Traverse all the elements numbered from @i@ to @j@ of a 'Seq'+--+-- >>> Seq.fromList [a,b,c,d,e] & sliced 1 3 %~ f+-- fromList [a,f b,f c,d,e]++-- >>> Seq.fromList [a,b,c,d,e] ^.. sliced 1 3+-- [f b,f c]+--+-- >>> Seq.fromList [a,b,c,d,e] & sliced 1 3 .~ x+-- fromList [a,x,x,b,e]+sliced :: Int -> Int -> IndexedTraversal' Int (Seq a) a+sliced i j f s = case Seq.splitAt i s of   (l,mr) -> case Seq.splitAt (j-i) mr of-     (m, r) -> (\n -> l >< n >< r) <$> itraverse (f . (+i)) m-{-# INLINE traverseSlice #-}+     (m, r) -> itraverse (indexed f . (+i)) m <&> \n -> l >< n >< r+{-# INLINE sliced #-}++-- | Construct a 'Seq' from a t'Getter', 'Control.Lens.Fold.Fold', 'Control.Lens.Traversal.Traversal', 'Control.Lens.Lens.Lens' or 'Control.Lens.Iso.Iso'.+--+-- >>> seqOf folded ["hello","world"]+-- fromList ["hello","world"]+--+-- >>> seqOf (folded._2) [("hello",1),("world",2),("!!!",3)]+-- fromList [1,2,3]+--+-- @+-- 'seqOf' :: t'Getter' s a    -> s -> 'Seq' a+-- 'seqOf' :: t'Fold' s a      -> s -> 'Seq' a+-- 'seqOf' :: 'Iso'' s a       -> s -> 'Seq' a+-- 'seqOf' :: 'Lens'' s a      -> s -> 'Seq' a+-- 'seqOf' :: 'Traversal'' s a -> s -> 'Seq' a+-- @+seqOf :: Getting (Seq a) s a -> s -> Seq a+seqOf l = views l Seq.singleton+{-# INLINE seqOf #-}
src/Data/Set/Lens.hs view
@@ -1,8 +1,14 @@+{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-}++{-# LANGUAGE Trustworthy #-}++#include "lens-common.h"+ ----------------------------------------------------------------------------- -- | -- Module      :  Data.Set.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional@@ -14,38 +20,45 @@   , setOf   ) where -import Control.Lens.Getter-import Control.Lens.Internal-import Control.Lens.Setter-import Data.Set as Set+import Control.Lens.Getter ( Getting, views )+import Control.Lens.Setter ( setting )+import Control.Lens.Type+import qualified Data.Set as Set+import Data.Set (Set) + -- $setup--- >>> :m + Data.Set.Lens Control.Lens+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import qualified Data.Set as Set  -- | This 'Setter' can be used to change the type of a 'Set' by mapping -- the elements to new values. ----- Sadly, you can't create a valid 'Control.Lens.Traversal.Traversal' for a 'Set', but you can+-- Sadly, you can't create a valid 'Traversal' for a 'Set', but you can -- manipulate it by reading using 'Control.Lens.Fold.folded' and reindexing it via 'setmapped'. ----- >>> over setmapped (+1) (fromList [1,2,3,4])+-- >>> over setmapped (+1) (Set.fromList [1,2,3,4]) -- fromList [2,3,4,5]-setmapped :: (Ord i, Ord j) => Setter (Set i) (Set j) i j-setmapped = sets Set.map+setmapped :: Ord j => IndexPreservingSetter (Set i) (Set j) i j+setmapped = setting Set.map {-# INLINE setmapped #-} --- | Construct a set from a 'Getter', 'Control.Lens.Fold.Fold', 'Control.Lens.Traversal.Traversal', 'Control.Lens.Type.Lens' or 'Control.Lens.Iso.Iso'.+-- | Construct a set from a 'Getter', 'Control.Lens.Fold.Fold', 'Control.Lens.Traversal.Traversal', 'Control.Lens.Lens.Lens' or 'Control.Lens.Iso.Iso'. --+-- >>> setOf folded ["hello","world"]+-- fromList ["hello","world"]+-- -- >>> setOf (folded._2) [("hello",1),("world",2),("!!!",3)] -- fromList [1,2,3] -- -- @--- 'setOf' ::          'Getter' a c           -> a -> 'Set' c--- 'setOf' :: 'Ord' c => 'Control.Lens.Fold.Fold' a c             -> a -> 'Set' c--- 'setOf' ::          'Control.Lens.Type.Simple' 'Control.Lens.Iso.Iso' a c       -> a -> 'Set' c--- 'setOf' ::          'Control.Lens.Type.Simple' 'Control.Lens.Type.Lens' a c      -> a -> 'Set' c--- 'setOf' :: 'Ord' c => 'Control.Lens.Type.Simple' 'Control.Lens.Traversal.Traversal' a c -> a -> 'Set' c+-- 'setOf' ::          'Getter' s a     -> s -> 'Set' a+-- 'setOf' :: 'Ord' a => 'Fold' s a       -> s -> 'Set' a+-- 'setOf' ::          'Iso'' s a       -> s -> 'Set' a+-- 'setOf' ::          'Lens'' s a      -> s -> 'Set' a+-- 'setOf' :: 'Ord' a => 'Traversal'' s a -> s -> 'Set' a -- @-setOf :: Getting (Set c) a b c d -> a -> Set c-setOf l = runAccessor . l (Accessor . Set.singleton)+setOf :: Getting (Set a) s a -> s -> Set a+setOf l = views l Set.singleton {-# INLINE setOf #-}
src/Data/Text/Lazy/Lens.hs view
@@ -1,36 +1,150 @@-{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-} ----------------------------------------------------------------------------- -- | -- Module      :  Data.Text.Lazy.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-2016 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  portable+-- Stability   :  experimental+-- Portability :  non-portable -- ---------------------------------------------------------------------------- module Data.Text.Lazy.Lens-  ( packed+  ( packed, unpacked+  , _Text   , text+  , builder+  , utf8+  , pattern Text   ) where -import Control.Lens-import Data.Text.Lazy+import Control.Lens.Type+import Control.Lens.Getter+import Control.Lens.Fold+import Control.Lens.Iso+import Control.Lens.Prism+import Control.Lens.Review+import Control.Lens.Setter+import Control.Lens.Traversal+import Data.ByteString.Lazy (ByteString)+import Data.Monoid+import Data.Text.Lazy (Text)+import qualified Data.Text.Lazy as Text+import qualified Data.Text.Lazy.Builder as Builder+import Data.Text.Lazy.Builder (Builder)+import Data.Text.Lazy.Encoding --- | Pack (or unpack) lazy 'Text'.+-- $setup+-- >>> :set -XOverloadedStrings+-- >>> import Control.Lens+-- >>> import qualified Data.ByteString.Lazy as ByteString++-- | This isomorphism can be used to 'pack' (or 'unpack') lazy 'Text'. --+-- >>> "hello"^.packed -- :: Text+-- "hello"+-- -- @--- 'pack' x = x '^.' 'packed'--- 'unpack' x = x '^.' 'from' 'packed'+-- 'pack' x ≡ x '^.' 'packed'+-- 'unpack' x ≡ x '^.' 'from' 'packed'+-- 'packed' ≡ 'from' 'unpacked' -- @-packed :: Simple Iso String Text-packed = iso pack unpack+packed :: Iso' String Text+packed = iso Text.pack Text.unpack {-# INLINE packed #-} +-- | This isomorphism can be used to 'unpack' (or 'pack') lazy 'Text'.+--+-- >>> "hello"^.unpacked -- :: String+-- "hello"+--+-- @+-- 'pack' x ≡ x '^.' 'from' 'unpacked'+-- 'unpack' x ≡ x '^.' 'packed'+-- @+--+-- This 'Iso' is provided for notational convenience rather than out of great need, since+--+-- @+-- 'unpacked' ≡ 'from' 'packed'+-- @+unpacked :: Iso' Text String+unpacked = iso Text.unpack Text.pack+{-# INLINE unpacked #-}++-- | This is an alias for 'unpacked' that makes it clearer how to use it with @('#')@.+--+-- @+-- '_Text' = 'from' 'packed'+-- @+--+-- >>> _Text # "hello" -- :: Text+-- "hello"+_Text :: Iso' Text String+_Text = from packed+{-# INLINE _Text #-}++-- | Convert between lazy 'Text' and 'Builder' .+--+-- @+-- 'fromLazyText' x ≡ x '^.' 'builder'+-- 'toLazyText' x ≡ x '^.' 'from' 'builder'+-- @+builder :: Iso' Text Builder+builder = iso Builder.fromLazyText Builder.toLazyText+{-# INLINE builder #-}+ -- | Traverse the individual characters in a 'Text'. ----- > anyOf text (=='c') :: Text -> Bool-text :: SimpleIndexedTraversal Int Text Char-text = from packed .> itraversed-{-# INLINE text #-}+-- >>> anyOf text (=='c') "chello"+-- True+--+-- @+-- 'text' = 'unpacked' . 'traversed'+-- @+--+-- When the type is unambiguous, you can also use the more general 'each'.+--+-- @+-- 'text' ≡ 'each'+-- @+--+-- Note that when just using this as a 'Setter', @'setting' 'Data.Text.Lazy.map'@+-- can be more efficient.+text :: IndexedTraversal' Int Text Char+text = unpacked . traversed+{-# INLINE [0] text #-}++{-# RULES+"lazy text -> map"    text = sets Text.map        :: ASetter' Text Char;+"lazy text -> imap"   text = isets imapLazy       :: AnIndexedSetter' Int Text Char;+"lazy text -> foldr"  text = foldring Text.foldr  :: Getting (Endo r) Text Char;+"lazy text -> ifoldr" text = ifoldring ifoldrLazy :: IndexedGetting Int (Endo r) Text Char;+ #-}++imapLazy :: (Int -> Char -> Char) -> Text -> Text+imapLazy f = snd . Text.mapAccumL (\i a -> i `seq` (i + 1, f i a)) 0+{-# INLINE imapLazy #-}++ifoldrLazy :: (Int -> Char -> a -> a) -> a -> Text -> a+ifoldrLazy f z xs = Text.foldr (\ x g i -> i `seq` f i x (g (i+1))) (const z) xs 0+{-# INLINE ifoldrLazy #-}++-- | Encode\/Decode a lazy 'Text' to\/from lazy 'ByteString', via UTF-8.+--+-- Note: This function does not decode lazily, as it must consume the entire+-- input before deciding whether or not it fails.+--+-- >>> ByteString.unpack (utf8 # "☃")+-- [226,152,131]+utf8 :: Prism' ByteString Text+utf8 = prism' encodeUtf8 (preview _Right . decodeUtf8')+{-# INLINE utf8 #-}++pattern Text :: String -> Text+pattern Text a <- (view _Text -> a) where+  Text a = review _Text a
src/Data/Text/Lens.hs view
@@ -1,47 +1,121 @@+{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE ViewPatterns #-}+{-# LANGUAGE PatternSynonyms #-} ----------------------------------------------------------------------------- -- | -- Module      :  Data.Text.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  portable+-- Stability   :  experimental+-- Portability :  non-portable -- ---------------------------------------------------------------------------- module Data.Text.Lens   ( IsText(..)+  , unpacked+  , _Text+  , pattern Text   ) where -import           Control.Lens-import           Data.Text as Strict+import           Control.Lens.Type+import           Control.Lens.Getter+import           Control.Lens.Review+import           Control.Lens.Iso+import           Control.Lens.Traversal+import qualified Data.Text as Strict import qualified Data.Text.Strict.Lens as Strict-import           Data.Text.Lazy as Lazy+import qualified Data.Text.Lazy as Lazy import qualified Data.Text.Lazy.Lens as Lazy+import           Data.Text.Lazy.Builder (Builder) +-- $setup+-- >>> import Control.Lens+-- >>> import qualified Data.Text as Strict+ -- | Traversals for strict or lazy 'Text' class IsText t where-  -- | 'pack' (or 'unpack') strict or lazy 'Text'.+  -- | This isomorphism can be used to 'pack' (or 'unpack') strict or lazy 'Text'.   --   -- @-  -- 'pack' x = x '^.' 'packed'-  -- 'unpack' x = x '^.' 'from' 'packed'+  -- 'pack' x ≡ x '^.' 'packed'+  -- 'unpack' x ≡ x '^.' 'from' 'packed'+  -- 'packed' ≡ 'from' 'unpacked'   -- @-  packed :: Simple Iso String t+  packed :: Iso' String t +  -- | Convert between strict or lazy 'Text' and a 'Builder'.+  --+  -- @+  -- 'fromText' x ≡ x '^.' 'builder'+  -- @+  builder :: Iso' t Builder+   -- | Traverse the individual characters in strict or lazy 'Text'.-  text :: SimpleIndexedTraversal Int t Char-  text = from packed .> itraversed+  --+  -- @+  -- 'text' = 'unpacked' . 'traversed'+  -- @+  text :: IndexedTraversal' Int t Char+  text = unpacked . traversed   {-# INLINE text #-} +instance IsText String where+  packed = id+  {-# INLINE packed #-}+  text = traversed+  {-# INLINE text #-}+  builder = Lazy.packed . builder+  {-# INLINE builder #-}++-- | This isomorphism can be used to 'unpack' (or 'pack') both strict or lazy 'Text'.+--+-- @+-- 'unpack' x ≡ x '^.' 'unpacked'+-- 'pack' x ≡ x '^.' 'from' 'unpacked'+-- @+--+-- This 'Iso' is provided for notational convenience rather than out of great need, since+--+-- @+-- 'unpacked' ≡ 'from' 'packed'+-- @+--+unpacked :: IsText t => Iso' t String+unpacked = from packed+{-# INLINE unpacked #-}++-- | This is an alias for 'unpacked' that makes it clearer how to use it with @('#')@.+--+-- @+-- '_Text' = 'from' 'packed'+-- @+--+-- >>> _Text # "hello" :: Strict.Text+-- "hello"+_Text :: IsText t => Iso' t String+_Text = from packed+{-# INLINE _Text #-}++pattern Text :: IsText s => String -> s+pattern Text a <- (view _Text -> a) where+  Text a = review _Text a+ instance IsText Strict.Text where   packed = Strict.packed   {-# INLINE packed #-}+  builder = Strict.builder+  {-# INLINE builder #-}   text = Strict.text   {-# INLINE text #-}  instance IsText Lazy.Text where   packed = Lazy.packed   {-# INLINE packed #-}+  builder = Lazy.builder+  {-# INLINE builder #-}   text = Lazy.text   {-# INLINE text #-}+
src/Data/Text/Strict/Lens.hs view
@@ -1,36 +1,142 @@ {-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-} ----------------------------------------------------------------------------- -- | -- Module      :  Data.Text.Strict.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-2016 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  portable+-- Stability   :  experimental+-- Portability :  non-portable -- ---------------------------------------------------------------------------- module Data.Text.Strict.Lens-  ( packed+  ( packed, unpacked+  , builder   , text+  , utf8+  , _Text+  , pattern Text   ) where -import Control.Lens-import Data.Text+import Control.Lens.Type+import Control.Lens.Getter+import Control.Lens.Fold+import Control.Lens.Iso+import Control.Lens.Prism+import Control.Lens.Review+import Control.Lens.Setter+import Control.Lens.Traversal+import Data.ByteString (ByteString)+import Data.Monoid+import qualified Data.Text as Strict+import Data.Text (Text)+import Data.Text.Encoding+import Data.Text.Lazy (toStrict)+import qualified Data.Text.Lazy.Builder as Builder+import Data.Text.Lazy.Builder (Builder) --- | 'pack' (or 'unpack') strict 'Text'.+-- $setup+-- >>> :set -XOverloadedStrings+-- >>> import Control.Lens++-- | This isomorphism can be used to 'pack' (or 'unpack') strict 'Text'. --+--+-- >>> "hello"^.packed -- :: Text+-- "hello"+-- -- @--- 'pack' x = x '^.' 'packed'--- 'unpack' x = x '^.' 'from' 'packed'+-- 'pack' x ≡ x '^.' 'packed'+-- 'unpack' x ≡ x '^.' 'from' 'packed'+-- 'packed' ≡ 'from' 'unpacked'+-- 'packed' ≡ 'iso' 'pack' 'unpack' -- @-packed :: Simple Iso String Text-packed = iso pack unpack+packed :: Iso' String Text+packed = iso Strict.pack Strict.unpack {-# INLINE packed #-} +-- | This isomorphism can be used to 'unpack' (or 'pack') lazy 'Text'.+--+-- >>> "hello"^.unpacked -- :: String+-- "hello"+--+-- This 'Iso' is provided for notational convenience rather than out of great need, since+--+-- @+-- 'unpacked' ≡ 'from' 'packed'+-- @+--+-- @+-- 'pack' x ≡ x '^.' 'from' 'unpacked'+-- 'unpack' x ≡ x '^.' 'packed'+-- 'unpacked' ≡ 'iso' 'unpack' 'pack'+-- @+unpacked :: Iso' Text String+unpacked = iso Strict.unpack Strict.pack+{-# INLINE unpacked #-}++-- | This is an alias for 'unpacked' that makes it more obvious how to use it with '#'+--+-- >> _Text # "hello" -- :: Text+-- "hello"+_Text :: Iso' Text String+_Text = unpacked+{-# INLINE _Text #-}++-- | Convert between strict 'Text' and 'Builder' .+--+-- @+-- 'fromText' x ≡ x '^.' 'builder'+-- 'toStrict' ('toLazyText' x) ≡ x '^.' 'from' 'builder'+-- @+builder :: Iso' Text Builder+builder = iso Builder.fromText (toStrict . Builder.toLazyText)+{-# INLINE builder #-}+ -- | Traverse the individual characters in strict 'Text'. ----- >>> anyOf text (=='o') $ "hello"^.packed+-- >>> anyOf text (=='o') "hello" -- True-text :: SimpleIndexedTraversal Int Text Char-text = from packed .> itraversed-{-# INLINE text #-}+--+-- When the type is unambiguous, you can also use the more general 'each'.+--+-- @+-- 'text' ≡ 'unpacked' . 'traversed'+-- 'text' ≡ 'each'+-- @+--+-- Note that when just using this as a 'Setter', @'setting' 'Data.Text.map'@ can+-- be more efficient.+text :: IndexedTraversal' Int Text Char+text = unpacked . traversed+{-# INLINE [0] text #-}++{-# RULES+"strict text -> map"    text = sets Strict.map        :: ASetter' Text Char;+"strict text -> imap"   text = isets imapStrict       :: AnIndexedSetter' Int Text Char;+"strict text -> foldr"  text = foldring Strict.foldr  :: Getting (Endo r) Text Char;+"strict text -> ifoldr" text = ifoldring ifoldrStrict :: IndexedGetting Int (Endo r) Text Char;+ #-}++imapStrict :: (Int -> Char -> Char) -> Text -> Text+imapStrict f = snd . Strict.mapAccumL (\i a -> i `seq` (i + 1, f i a)) 0+{-# INLINE imapStrict #-}++ifoldrStrict :: (Int -> Char -> a -> a) -> a -> Text -> a+ifoldrStrict f z xs = Strict.foldr (\ x g i -> i `seq` f i x (g (i+1))) (const z) xs 0+{-# INLINE ifoldrStrict #-}++-- | Encode\/Decode a strict 'Text' to\/from strict 'ByteString', via UTF-8.+--+-- >>> utf8 # "☃"+-- "\226\152\131"+utf8 :: Prism' ByteString Text+utf8 = prism' encodeUtf8 (preview _Right . decodeUtf8')+{-# INLINE utf8 #-}++pattern Text :: String -> Text+pattern Text a <- (view _Text -> a) where+  Text a = review _Text a
src/Data/Tree/Lens.hs view
@@ -1,8 +1,10 @@ {-# LANGUAGE FlexibleContexts #-}++ ----------------------------------------------------------------------------- -- | -- Module      :  Data.Tree.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  provisional@@ -15,23 +17,27 @@   , branches   ) where +import Prelude ()++import Control.Lens.Internal.Prelude import Control.Lens-import Data.Functor-import Data.List.Lens import Data.Tree --- | A 'Lens' that focuses on the root of a 'Tree'.+-- $setup+-- >>> import Control.Lens+-- >>> import Data.Tree++-- | A t'Lens' that focuses on the root of a 'Tree'. -- -- >>> view root $ Node 42 [] -- 42-root :: Simple Lens (Tree a) a+root :: Lens' (Tree a) a root f (Node a as) = (`Node` as) <$> f a {-# INLINE root #-} --- | A 'Traversal' of the direct descendants of the root of a 'Tree'--- indexed by its position in the list of children+-- | A t'Lens' returning the direct descendants of the root of a 'Tree' ----- @'toListOf' 'branches' ≡ 'subForest'@-branches :: SimpleIndexedTraversal Int (Tree a) (Tree a)-branches = index $ \ f (Node a as) -> Node a <$> withIndex traverseList f as+-- @'view' 'branches' ≡ 'subForest'@+branches :: Lens' (Tree a) [Tree a]+branches f (Node a as) = Node a <$> f as {-# INLINE branches #-}
src/Data/Typeable/Lens.hs view
@@ -1,8 +1,9 @@ {-# LANGUAGE Rank2Types #-}+ ----------------------------------------------------------------------------- -- | -- Module      :  Data.Typeable.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  experimental@@ -14,21 +15,23 @@   , _gcast   ) where -import Control.Applicative+import Prelude ()+ import Control.Lens+import Control.Lens.Internal.Prelude+import Data.Maybe (fromMaybe) import Data.Typeable-import Unsafe.Coerce as Unsafe --- | A 'Simple' 'Traversal' for working with a 'cast' of a 'Typeable' value.-_cast :: (Typeable a, Typeable b) => Simple Traversal a b-_cast f a = case cast a of-  Just b  -> Unsafe.unsafeCoerce <$> f b-  Nothing -> pure a+-- | A 'Traversal'' for working with a 'cast' of a 'Typeable' value.+_cast :: (Typeable s, Typeable a) => Traversal' s a+_cast f s = case cast s of+  Just a  -> fromMaybe (error "_cast: recast failed") . cast <$> f a+  Nothing -> pure s {-# INLINE _cast #-} --- | A 'Simple' 'Traversal' for working with a 'gcast' of a 'Typeable' value.-_gcast :: (Typeable a, Typeable b) => Simple Traversal (c a) (c b)-_gcast f a = case gcast a of-  Just b  -> Unsafe.unsafeCoerce <$> f b-  Nothing -> pure a+-- | A 'Traversal'' for working with a 'gcast' of a 'Typeable' value.+_gcast :: (Typeable s, Typeable a) => Traversal' (c s) (c a)+_gcast f s = case gcast s of+  Just a  -> fromMaybe (error "_gcast: recast failed") . gcast <$> f a+  Nothing -> pure s {-# INLINE _gcast #-}
+ src/Data/Vector/Generic/Lens.hs view
@@ -0,0 +1,153 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE FlexibleContexts #-}+#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-}+#endif++#include "lens-common.h"++-------------------------------------------------------------------------------+-- |+-- Module      :  Data.Vector.Generic.Lens+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  non-portable+--+-- This module provides lenses and traversals for working with generic+-- vectors.+-------------------------------------------------------------------------------+module Data.Vector.Generic.Lens+  ( toVectorOf+  -- * Isomorphisms+  , forced+  , vector+  , asStream+  , asStreamR+  , cloned+  , converted+  -- * Lenses+  , sliced+  -- * Traversal of individual indices+  , ordinals+  , vectorIx+  , vectorTraverse+  ) where++import Prelude ()++import Control.Lens.Type+import Control.Lens.Lens+import Control.Lens.Getter+import Control.Lens.Fold+import Control.Lens.Iso+import Control.Lens.Indexed+import Control.Lens.Setter+import Control.Lens.Traversal+import Control.Lens.Internal.List (ordinalNub)+import Control.Lens.Internal.Prelude+import Data.Vector.Fusion.Bundle (Bundle)+import qualified Data.Vector.Generic as V+import Data.Vector.Generic (Vector)+import Data.Vector.Generic.New (New)++-- $setup+-- >>> import qualified Data.Vector as Vector+-- >>> import Control.Lens++-- | @sliced i n@ provides a 'Lens' that edits the @n@ elements starting+-- at index @i@ from a 'Lens'.+--+-- This is only a valid 'Lens' if you do not change the length of the+-- resulting 'Vector'.+--+-- Attempting to return a longer or shorter vector will result in+-- violations of the 'Lens' laws.+--+-- >>> Vector.fromList [1..10] ^. sliced 2 5 == Vector.fromList [3,4,5,6,7]+-- True+--+-- >>> (Vector.fromList [1..10] & sliced 2 5 . mapped .~ 0) == Vector.fromList [1,2,0,0,0,0,0,8,9,10]+-- True+sliced :: Vector v a+       => Int -- ^ @i@ starting index+       -> Int -- ^ @n@ length+       -> Lens' (v a) (v a)+sliced i n f v = f (V.slice i n v) <&> \ v0 -> v V.// zip [i..i+n-1] (V.toList v0)+{-# INLINE sliced #-}++-- | Similar to 'toListOf', but returning a 'Vector'.+--+-- >>> (toVectorOf both (8,15) :: Vector.Vector Int) == Vector.fromList [8,15]+-- True+toVectorOf :: Vector v a => Getting (Endo [a]) s a -> s -> v a+toVectorOf l s = V.fromList (toListOf l s)+{-# INLINE toVectorOf #-}++-- | Convert a list to a 'Vector' (or back.)+--+-- >>> ([1,2,3] ^. vector :: Vector.Vector Int) == Vector.fromList [1,2,3]+-- True+--+-- >>> Vector.fromList [0,8,15] ^. from vector+-- [0,8,15]+vector :: (Vector v a, Vector v b) => Iso [a] [b] (v a) (v b)+vector = iso V.fromList V.toList+{-# INLINE vector #-}++-- | Convert a 'Vector' to a finite 'Bundle' (or back.)+asStream :: (Vector v a, Vector v b) => Iso (v a) (v b) (Bundle v a) (Bundle v b)+asStream = iso V.stream V.unstream+{-# INLINE asStream #-}++-- | Convert a 'Vector' to a finite 'Bundle' from right to left (or+-- back.)+asStreamR :: (Vector v a, Vector v b) => Iso (v a) (v b) (Bundle v a) (Bundle v b)+asStreamR = iso V.streamR V.unstreamR+{-# INLINE asStreamR #-}++-- | Convert a 'Vector' back and forth to an initializer that when run+-- produces a copy of the 'Vector'.+cloned :: Vector v a => Iso' (v a) (New v a)+cloned = iso V.clone V.new+{-# INLINE cloned #-}++-- | Convert a 'Vector' to a version that doesn't retain any extra+-- memory.+forced :: Vector v a => Iso' (v a) (v a)+forced = involuted V.force+{-# INLINE forced #-}++-- | This 'Traversal' will ignore any duplicates in the supplied list+-- of indices.+--+-- >>> toListOf (ordinals [1,3,2,5,9,10]) $ Vector.fromList [2,4..40]+-- [4,8,6,12,20,22]+ordinals :: Vector v a => [Int] -> IndexedTraversal' Int (v a) a+ordinals is f v = fmap (v V.//) $ traverse (\i -> (,) i <$> indexed f i (v V.! i)) $ ordinalNub (V.length v) is+{-# INLINE ordinals #-}++-- | Like 'ix' but polymorphic in the vector type.+vectorIx :: V.Vector v a => Int -> Traversal' (v a) a+vectorIx i f v+  | 0 <= i && i < V.length v = f (v V.! i) <&> \a -> v V.// [(i, a)]+  | otherwise                = pure v+{-# INLINE vectorIx #-}++-- | Indexed vector traversal for a generic vector.+vectorTraverse :: (V.Vector v a, V.Vector w b) => IndexedTraversal Int (v a) (w b) a b+vectorTraverse f v = V.fromListN (V.length v) <$> traversed f (V.toList v)+{-# INLINE [0] vectorTraverse #-}++{-# RULES+"vectorTraverse -> mapped" vectorTraverse  = sets V.map         :: (V.Vector v a, V.Vector v b) => ASetter (v a) (v b) a b;+"vectorTraverse -> imapped" vectorTraverse = isets V.imap       :: (V.Vector v a, V.Vector v b) => AnIndexedSetter Int (v a) (v b) a b;+"vectorTraverse -> foldr"  vectorTraverse  = foldring V.foldr   :: V.Vector v a => Getting (Endo r) (v a) a;+"vectorTraverse -> ifoldr" vectorTraverse  = ifoldring V.ifoldr :: V.Vector v a => IndexedGetting Int (Endo r) (v a) a;+ #-}++-- | Different vector implementations are isomorphic to each other.+converted :: (Vector v a, Vector w a, Vector v b, Vector w b) => Iso (v a) (v b) (w a) (w b)+converted = iso V.convert V.convert
+ src/Data/Vector/Lens.hs view
@@ -0,0 +1,98 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE MultiParamTypeClasses #-}+#ifdef TRUSTWORTHY+{-# LANGUAGE Trustworthy #-}+#endif+-------------------------------------------------------------------------------+-- |+-- Module      :  Data.Vector.Lens+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  non-portable+--+-- This module provides lenses and traversals for working with generic+-- vectors.+-------------------------------------------------------------------------------+module Data.Vector.Lens+  ( toVectorOf+  -- * Isomorphisms+  , vector+  , forced+  -- * Lenses+  , sliced+  -- * Traversal of individual indices+  , ordinals+  ) where++import Prelude ()++import Control.Lens+import Control.Lens.Internal.List (ordinalNub)+import Control.Lens.Internal.Prelude+import qualified Data.Vector as V+import Data.Vector (Vector)++-- $setup+-- >>> import qualified Data.Vector as Vector+-- >>> import Control.Lens++-- | @sliced i n@ provides a t'Lens' that edits the @n@ elements starting+-- at index @i@ from a t'Lens'.+--+-- This is only a valid t'Lens' if you do not change the length of the+-- resulting 'Vector'.+--+-- Attempting to return a longer or shorter vector will result in+-- violations of the t'Lens' laws.+--+-- >>> Vector.fromList [1..10] ^. sliced 2 5 == Vector.fromList [3,4,5,6,7]+-- True+--+-- >>> (Vector.fromList [1..10] & sliced 2 5 . mapped .~ 0) == Vector.fromList [1,2,0,0,0,0,0,8,9,10]+-- True+sliced :: Int -- ^ @i@ starting index+       -> Int -- ^ @n@ length+       -> Lens' (Vector a) (Vector a)+sliced i n f v = f (V.slice i n v) <&> \ v0 -> v V.// zip [i..i+n-1] (V.toList v0)+{-# INLINE sliced #-}++-- | Similar to 'toListOf', but returning a 'Vector'.+--+-- >>> toVectorOf both (8,15) == Vector.fromList [8,15]+-- True+toVectorOf :: Getting (Endo [a]) s a -> s -> Vector a+toVectorOf l s = V.fromList (toListOf l s)+{-# INLINE toVectorOf #-}++-- | Convert a list to a 'Vector' (or back)+--+-- >>> [1,2,3] ^. vector == Vector.fromList [1,2,3]+-- True+--+-- >>> [1,2,3] ^. vector . from vector+-- [1,2,3]+--+-- >>> Vector.fromList [0,8,15] ^. from vector . vector == Vector.fromList [0,8,15]+-- True+vector :: Iso [a] [b] (Vector a) (Vector b)+vector = iso V.fromList V.toList+{-# INLINE vector #-}++-- | Convert a 'Vector' to a version that doesn't retain any extra+-- memory.+forced :: Iso (Vector a) (Vector b) (Vector a) (Vector b)+forced = iso V.force V.force+{-# INLINE forced #-}++-- | This t'Traversal' will ignore any duplicates in the supplied list+-- of indices.+--+-- >>> toListOf (ordinals [1,3,2,5,9,10]) $ Vector.fromList [2,4..40]+-- [4,8,6,12,20,22]+ordinals :: [Int] -> IndexedTraversal' Int (Vector a) a+ordinals is f v = fmap (v V.//) $ traverse (\i -> (,) i <$> indexed f i (v V.! i)) $ ordinalNub (length v) is+{-# INLINE ordinals #-}
src/GHC/Generics/Lens.hs view
@@ -1,11 +1,14 @@+{-# LANGUAGE EmptyCase #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE MagicHash #-}+{-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE LiberalTypeSynonyms #-}-{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE PolyKinds #-} ----------------------------------------------------------------------------- -- | -- Module      :  GHC.Generics.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  experimental@@ -22,74 +25,135 @@ -- You can use 'generic' to replace 'GHC.Generics.from' and 'GHC.Generics.to' from @GHC.Generics@, -- and probably won't be explicitly referencing 'Control.Lens.Representable.Rep' from @Control.Lens@ -- in code that uses generics.+--+-- This module provides compatibility with older GHC versions by using the+-- <http://hackage.haskell.org/package/generic-deriving generic-deriving>+-- package. ---------------------------------------------------------------------------- module GHC.Generics.Lens   (-  -- * Isomorphisms for @GHC.Generics@     generic   , generic1-  -- * Generic Traversal-  , tinplate-  , GTraversal+  , _V1+  , _U1+  , _Par1+  , _Rec1+  , _K1+  , _M1+  , _L1+  , _R1+  , _UAddr+  , _UChar+  , _UDouble+  , _UFloat+  , _UInt+  , _UWord   ) where -import           Control.Applicative-import           Control.Lens hiding (Rep)-import           Data.Maybe (fromJust)-import           Data.Typeable+import           Control.Lens+import           GHC.Exts (Char(..), Double(..), Float(..),+                           Int(..), Ptr(..), Word(..)) import qualified GHC.Generics as Generic-import           GHC.Generics                     hiding (from, to)+import           GHC.Generics hiding (from, to) +-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+ -- | Convert from the data type to its representation (or back) -- -- >>> "hello"^.generic.from generic :: String -- "hello"----generic :: Generic a => Simple Iso a (Rep a b)+generic :: (Generic a, Generic b) => Iso a b (Rep a g) (Rep b h) generic = iso Generic.from Generic.to+{-# INLINE generic #-}  -- | Convert from the data type to its representation (or back)-generic1 :: Generic1 f => Simple Iso (f a) (Rep1 f a)+generic1 :: (Generic1 f, Generic1 g) => Iso (f a) (g b) (Rep1 f a) (Rep1 g b) generic1 = iso from1 to1+{-# INLINE generic1 #-} --- | A 'GHC.Generics.Generic' 'Traversal' that visits every occurence--- of something 'Typeable' anywhere in a container.------ >>> allOf tinplate (=="Hello") (1::Int,2::Double,(),"Hello",["Hello"])--- True------ >>> mapMOf_ tinplate putStrLn ("hello",[(2 :: Int, "world!")])--- hello--- world!-tinplate :: (Generic a, GTraversal (Rep a), Typeable b) => Simple Traversal a b-tinplate = generic . tinplated True+_V1 :: Over p f (V1 s) (V1 t) a b+_V1 _ = \case+{-# INLINE _V1 #-} -maybeArg1Of :: Maybe c -> (c -> d) -> Maybe c-maybeArg1Of = const+_U1 :: Iso (U1 p) (U1 q) () ()+_U1 = iso (const ()) (const U1)+{-# INLINE _U1 #-} --- | Used to traverse 'Generic' data by 'uniplate'.-class GTraversal f where-  tinplated :: Typeable b => Bool -> Simple Traversal (f a) b+_Par1 :: Iso (Par1 p) (Par1 q) p q+_Par1 = coerced+{-# INLINE _Par1 #-} -instance (Generic a, GTraversal (Rep a), Typeable a) => GTraversal (K1 i a) where-  tinplated rec f (K1 a) = case cast a `maybeArg1Of` f of-    Just b  -> K1 . fromJust . cast <$> f b-    Nothing | rec       -> K1 <$> fmap generic (tinplated False) f a-            | otherwise -> pure $ K1 a+_Rec1 :: Iso (Rec1 f p) (Rec1 g q) (f p) (g q)+_Rec1 = coerced+{-# INLINE _Rec1 #-} -instance GTraversal U1 where-  tinplated _ _ U1 = pure U1+_K1 :: Iso (K1 i c p) (K1 j d q) c d+_K1 = coerced+{-# INLINE _K1 #-} -instance (GTraversal f, GTraversal g) => GTraversal (f :*: g) where-  tinplated _ f (x :*: y) = (:*:) <$> tinplated True f x <*> tinplated True f y+_M1 :: Iso (M1 i c f p) (M1 j d g q) (f p) (g q)+_M1 = coerced+{-# INLINE _M1 #-} -instance (GTraversal f, GTraversal g) => GTraversal (f :+: g) where-  tinplated _ f (L1 x) = L1 <$> tinplated True f x-  tinplated _ f (R1 x) = R1 <$> tinplated True f x+_L1 :: Prism' ((f :+: g) a) (f a)+_L1 = prism remitter reviewer+  where+  remitter = L1+  reviewer (L1 l) = Right l+  reviewer x = Left x+{-# INLINE _L1 #-} -instance GTraversal a => GTraversal (M1 i c a) where-  tinplated rec f (M1 x) = M1 <$> tinplated rec f x+-- | You can access fields of `data (f :*: g) p` by using its `Field1` and+-- `Field2` instances. --- ?-instance (Traversable f, GTraversal g) => GTraversal (f :.: g) where-  tinplated _ f (Comp1 fgp) = Comp1 <$> traverse (tinplated True f) fgp+_R1 :: Prism' ((f :+: g) a) (g a)+_R1 = prism remitter reviewer+  where+  remitter = R1+  reviewer (R1 l) = Right l+  reviewer x = Left x+{-# INLINE _R1 #-}++_UAddr :: Iso (UAddr p) (UAddr q) (Ptr c) (Ptr d)+_UAddr = iso remitter reviewer+  where+  remitter (UAddr a) = Ptr a+  reviewer (Ptr a) = UAddr a+{-# INLINE _UAddr #-}++_UChar :: Iso (UChar p) (UChar q) Char Char+_UChar = iso remitter reviewer+  where+  remitter (UChar c) = C# c+  reviewer (C# c) = UChar c+{-# INLINE _UChar #-}++_UDouble :: Iso (UDouble p) (UDouble q) Double Double+_UDouble = iso remitter reviewer+  where+  remitter (UDouble d) = D# d+  reviewer (D# d) = UDouble d+{-# INLINE _UDouble #-}++_UFloat :: Iso (UFloat p) (UFloat q) Float Float+_UFloat = iso remitter reviewer+  where+  remitter (UFloat f) = F# f+  reviewer (F# f) = UFloat f+{-# INLINE _UFloat #-}++_UInt :: Iso (UInt p) (UInt q) Int Int+_UInt = iso remitter reviewer+  where+  remitter (UInt i) = I# i+  reviewer (I# i) = UInt i+{-# INLINE _UInt #-}++_UWord :: Iso (UWord p) (UWord q) Word Word+_UWord = iso remitter reviewer+  where+  remitter (UWord w) = W# w+  reviewer (W# w) = UWord w+{-# INLINE _UWord #-}
src/Language/Haskell/TH/Lens.hs view
@@ -1,130 +1,2986 @@ {-# LANGUAGE CPP #-}-{-# LANGUAGE TemplateHaskell #-}-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 704-{-# LANGUAGE Trustworthy #-}-#endif-{-# LANGUAGE Rank2Types #-}--------------------------------------------------------------------------------- |--- Module      :  Language.Haskell.TH.Lens--- Copyright   :  (C) 2012 Edward Kmett--- License     :  BSD-style (see the file LICENSE)--- Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  experimental--- Portability :  TemplateHaskell------ Lenses and Traversals for working with Template Haskell------------------------------------------------------------------------------module Language.Haskell.TH.Lens-  ( HasName(..)-  , HasTypeVars(..)-  , SubstType(..)-  , typeVars      -- :: HasTypeVars t => Simple Traversal t Name-  , substTypeVars -- :: HasTypeVars t => Map Name Name -> t -> t-  , conFields-  , conNamedFields-  ) where--import Control.Applicative-import Control.Lens.Getter-import Control.Lens.Setter-import Control.Lens.Type-import Control.Lens.Traversal-import Control.Lens.IndexedLens-import Data.Map as Map hiding (toList,map)-import Data.Maybe (fromMaybe)-import Data.Monoid-import Data.Set as Set hiding (toList,map)-import Data.Set.Lens-import Language.Haskell.TH-import Language.Haskell.TH.Syntax---- | Has a 'Name'-class HasName t where-  -- | Extract (or modify) the 'Name' of something-  name :: Simple Lens t Name--instance HasName TyVarBndr where-  name f (PlainTV n) = PlainTV <$> f n-  name f (KindedTV n k) = (`KindedTV` k) <$> f n--instance HasName Name where-  name = id--instance HasName Con where-  name f (NormalC n tys)       = (`NormalC` tys) <$> f n-  name f (RecC n tys)          = (`RecC` tys) <$> f n-  name f (InfixC l n r)        = (\n' -> InfixC l n' r) <$> f n-  name f (ForallC bds ctx con) = ForallC bds ctx <$> name f con---- | Provides for the extraction of free type variables, and alpha renaming.-class HasTypeVars t where-  -- | When performing substitution into this traversal you're not allowed-  -- to substitute in a name that is bound internally or you'll violate-  -- the 'Traversal' laws, when in doubt generate your names with 'newName'.-  typeVarsEx :: Set Name -> Simple Traversal t Name--instance HasTypeVars TyVarBndr where-  typeVarsEx s f b-    | s^.contains (b^.name) = pure b-    | otherwise             = name f b--instance HasTypeVars Name where-  typeVarsEx s f n-    | s^.contains n = pure n-    | otherwise     = f n--instance HasTypeVars Type where-  typeVarsEx s f (VarT n)            = VarT <$> typeVarsEx s f n-  typeVarsEx s f (AppT l r)          = AppT <$> typeVarsEx s f l <*> typeVarsEx s f r-  typeVarsEx s f (SigT t k)          = (`SigT` k) <$> typeVarsEx s f t-  typeVarsEx s f (ForallT bs ctx ty) = ForallT bs <$> typeVarsEx s' f ctx <*> typeVarsEx s' f ty-       where s' = s `Set.union` setOf typeVars bs-  typeVarsEx _ _ t                   = pure t--instance HasTypeVars Pred where-  typeVarsEx s f (ClassP n ts) = ClassP n <$> typeVarsEx s f ts-  typeVarsEx s f (EqualP l r)  = EqualP <$> typeVarsEx s f l <*> typeVarsEx s f r--instance HasTypeVars t => HasTypeVars [t] where-  typeVarsEx s = traverse . typeVarsEx s---- | Traverse /free/ type variables-typeVars :: HasTypeVars t => Simple Traversal t Name-typeVars = typeVarsEx mempty---- | Substitute using a map of names in for /free/ type variables-substTypeVars :: HasTypeVars t => Map Name Name -> t -> t-substTypeVars m = mapOf typeVars $ \n -> fromMaybe n (m^.at n)---- | Provides substitution for types-class SubstType t where-  -- | Perform substitution for types-  substType :: Map Name Type -> t -> t--instance SubstType Type where-  substType m t@(VarT n)          = fromMaybe t (m^.at n)-  substType m (ForallT bs ctx ty) = ForallT bs (substType m ctx) (substType m ty)-  substType m (SigT t k)          = SigT (substType m t) k-  substType m (AppT l r)          = AppT (substType m l) (substType m r)-  substType _ t                   = t--instance SubstType t => SubstType [t] where-  substType = map . substType--instance SubstType Pred where-  substType m (ClassP n ts) = ClassP n (substType m ts)-  substType m (EqualP l r)  = substType m (EqualP l r)---- | Provides a 'Traversal' of the types of each field of a constructor.-conFields :: Simple Traversal Con StrictType-conFields f (NormalC n fs)      = NormalC n <$> traverse f fs-conFields f (RecC n fs)         = RecC n <$> traverse sans_var fs-  where sans_var (fn,s,t) = (\(s', t') -> (fn,s',t')) <$> f (s, t)-conFields f (InfixC l n r)      = InfixC <$> f l <*> pure n <*> f r-conFields f (ForallC bds ctx c) = ForallC bds ctx <$> conFields f c---- | 'Traversal' of the types of the /named/ fields of a constructor.-conNamedFields :: Simple Traversal Con VarStrictType-conNamedFields f (RecC n fs) = RecC n <$> traverse f fs-conNamedFields _ c = pure c+{-# LANGUAGE FlexibleInstances #-}+#if defined(__GLASGOW_HASKELL__)+{-# LANGUAGE Trustworthy #-}+#endif+{-# LANGUAGE Rank2Types #-}++#include "lens-common.h"++-----------------------------------------------------------------------------+-- |+-- Module      :  Language.Haskell.TH.Lens+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  TemplateHaskell+--+-- Lenses, Prisms, and Traversals for working with Template Haskell.+--+-- Beware that the API offered in this module is subject to change, as it+-- mirrors the API exposed by the @template-haskell@ package, which+-- frequently changes between different releases of GHC. An effort is made+-- to identify the functions in this module which have different type+-- signatures when compiled with different versions of @template-haskell@.+----------------------------------------------------------------------------+module Language.Haskell.TH.Lens+  (+  -- * Traversals+    HasName(..)+  , HasTypes(..)+  , HasTypeVars(..)+  , SubstType(..)+  , typeVars      -- :: HasTypeVars t => Traversal' t Name+  , substTypeVars -- :: HasTypeVars t => Map Name Name -> t -> t+  , conFields+  , conNamedFields+  -- * Lenses+  -- ** Loc Lenses+  , locFileName+  , locPackage+  , locModule+  , locStart+  , locEnd+  -- ** FunDep Lenses+  , funDepInputs+  , funDepOutputs+  -- ** Match Lenses+  , matchPattern+  , matchBody+  , matchDeclarations+  -- ** Fixity Lenses+  , fixityPrecedence+  , fixityDirection+  -- ** Clause Lenses+  , clausePattern+  , clauseBody+  , clauseDecs+  -- ** FieldExp Lenses+  , fieldExpName+  , fieldExpExpression+  -- ** FieldPat Lenses+  , fieldPatName+  , fieldPatPattern+  -- ** TySynEqn Lenses+# if MIN_VERSION_template_haskell(2,15,0)+  , tySynEqnLHS+# endif+  , tySynEqnPatterns+  , tySynEqnResult+  -- ** InjectivityAnn Lenses+  , injectivityAnnOutput+  , injectivityAnnInputs+  -- ** TypeFamilyHead Lenses+  , typeFamilyHeadName+  , typeFamilyHeadTyVarBndrs+  , typeFamilyHeadResultSig+  , typeFamilyHeadInjectivityAnn+  -- ** Bang Lenses+  , bangSourceUnpackedness+  , bangSourceStrictness+#if MIN_VERSION_template_haskell(2,12,0)+  -- ** DerivClause Lenses+  , derivClauseStrategy+  , derivClauseCxt+#endif+  -- * Prisms+  -- ** Info Prisms+  , _ClassI+  , _ClassOpI+  , _TyConI+  , _FamilyI+  , _PrimTyConI+  , _DataConI+  , _VarI+  , _TyVarI+#if MIN_VERSION_template_haskell(2,12,0)+  , _PatSynI+#endif+  -- ** Dec Prisms+  , _FunD+  , _ValD+  , _DataD+  , _NewtypeD+  , _TySynD+  , _ClassD+  , _InstanceD+  , _SigD+  , _ForeignD+  , _InfixD+  , _PragmaD+  , _DataInstD+  , _NewtypeInstD+  , _TySynInstD+  , _ClosedTypeFamilyD+  , _RoleAnnotD+  , _StandaloneDerivD+  , _DefaultSigD+  , _DataFamilyD+  , _OpenTypeFamilyD+#if MIN_VERSION_template_haskell(2,12,0)+  , _PatSynD+  , _PatSynSigD+#endif+#if MIN_VERSION_template_haskell(2,15,0)+  , _ImplicitParamBindD+#endif+#if MIN_VERSION_template_haskell(2,19,0)+  , _DefaultD+#endif+#if MIN_VERSION_template_haskell(2,20,0)+  , _TypeDataD+#endif+#if MIN_VERSION_template_haskell(2,12,0)+  -- ** PatSynDir Prisms+  , _Unidir+  , _ImplBidir+  , _ExplBidir+  -- ** PatSynArgs Prisms+  , _PrefixPatSyn+  , _InfixPatSyn+  , _RecordPatSyn+#endif+  -- ** Con Prisms+  , _NormalC+  , _RecC+  , _InfixC+  , _ForallC+  , _GadtC+  , _RecGadtC+#if MIN_VERSION_template_haskell(2,22,0)+  -- ** NamespaceSpecifier Prisms+  , _NoNamespaceSpecifier+  , _TypeNamespaceSpecifier+  , _DataNamespaceSpecifier+#endif+  -- ** Overlap Prisms+  ,_Overlappable+  ,_Overlapping+  ,_Overlaps+  ,_Incoherent+  -- ** SourceUnpackedness Prisms+  , _NoSourceUnpackedness+  , _SourceNoUnpack+  , _SourceUnpack+  -- ** SourceStrictness Prisms+  , _NoSourceStrictness+  , _SourceLazy+  , _SourceStrict+  -- ** DecidedStrictness Prisms+  , _DecidedLazy+  , _DecidedStrict+  , _DecidedUnpack+  -- ** Foreign Prisms+  , _ImportF+  , _ExportF+  -- ** Callconv Prisms+  , _CCall+  , _StdCall+  , _CApi+  , _Prim+  , _JavaScript+  -- ** Safety Prisms+  , _Unsafe+  , _Safe+  , _Interruptible+  -- ** Pragma Prisms+  , _InlineP+  , _SpecialiseP+  , _SpecialiseInstP+  , _RuleP+  , _AnnP+  , _LineP+#if MIN_VERSION_template_haskell(2,12,0)+  , _CompleteP+#endif+#if MIN_VERSION_template_haskell(2,19,0)+  , _OpaqueP+#endif+#if MIN_VERSION_template_haskell(2,22,0)+  , _SCCP+#endif+#if MIN_VERSION_template_haskell(2,24,0)+  , _SpecialiseEP+#endif+  -- ** Inline Prisms+  , _NoInline+  , _Inline+  , _Inlinable+  -- ** RuleMatch Prisms+  , _ConLike+  , _FunLike+  -- ** Phases Prisms+  , _AllPhases+  , _FromPhase+  , _BeforePhase+  -- ** RuleBndr Prisms+  , _RuleVar+  , _TypedRuleVar+  -- ** AnnTarget Prisms+  , _ModuleAnnotation+  , _TypeAnnotation+  , _ValueAnnotation+  -- ** FunDep Prisms TODO make a lens+  , _FunDep+#if !(MIN_VERSION_template_haskell(2,13,0))+  -- ** FamFlavour Prisms+  , _TypeFam+  , _DataFam+#endif+  -- ** FixityDirection Prisms+  , _InfixL+  , _InfixR+  , _InfixN+  -- ** Exp Prisms+  , _VarE+  , _ConE+  , _LitE+  , _AppE+#if MIN_VERSION_template_haskell(2,12,0)+  , _AppTypeE+#endif+  , _InfixE+  , _UInfixE+  , _ParensE+  , _LamE+  , _LamCaseE+  , _TupE+  , _UnboxedTupE+#if MIN_VERSION_template_haskell(2,12,0)+  , _UnboxedSumE+#endif+  , _CondE+  , _MultiIfE+  , _LetE+  , _CaseE+  , _DoE+  , _CompE+  , _ArithSeqE+  , _ListE+  , _SigE+  , _RecConE+  , _RecUpdE+  , _StaticE+  , _UnboundVarE+#if MIN_VERSION_template_haskell(2,13,0)+  , _LabelE+#endif+#if MIN_VERSION_template_haskell(2,15,0)+  , _MDoE+  , _ImplicitParamVarE+#endif+#if MIN_VERSION_template_haskell(2,18,0)+  , _GetFieldE+  , _ProjectionE+#endif+#if MIN_VERSION_template_haskell(2,19,0)+  , _LamCasesE+#endif+#if MIN_VERSION_template_haskell(2,21,0)+  , _TypedBracketE+  , _TypedSpliceE+#endif+#if MIN_VERSION_template_haskell(2,22,0)+  , _TypeE+#endif+#if MIN_VERSION_template_haskell(2,23,0)+  , _ForallE+  , _ForallVisE+  , _ConstrainedE+#endif+  -- ** Body Prisms+  , _GuardedB+  , _NormalB+  -- ** Guard Prisms+  , _NormalG+  , _PatG+  -- ** Stmt Prisms+  , _BindS+  , _LetS+  , _NoBindS+  , _ParS+#if MIN_VERSION_template_haskell(2,15,0)+  , _RecS+#endif+  -- ** Range Prisms+  , _FromR+  , _FromThenR+  , _FromToR+  , _FromThenToR+  -- ** Lit Prisms+  , _CharL+  , _StringL+  , _IntegerL+  , _RationalL+  , _IntPrimL+  , _WordPrimL+  , _FloatPrimL+  , _DoublePrimL+  , _StringPrimL+  , _CharPrimL+#if MIN_VERSION_template_haskell(2,16,0)+  , _BytesPrimL+#endif+  -- ** Pat Prisms+  , _LitP+  , _VarP+  , _TupP+  , _UnboxedTupP+#if MIN_VERSION_template_haskell(2,12,0)+  , _UnboxedSumP+#endif+  , _ConP+  , _InfixP+  , _UInfixP+  , _ParensP+  , _TildeP+  , _BangP+  , _AsP+  , _WildP+  , _RecP+  , _ListP+  , _SigP+  , _ViewP+#if MIN_VERSION_template_haskell(2,22,0)+  , _TypeP+  , _InvisP+#endif+#if MIN_VERSION_template_haskell(2,23,0)+  , _OrP+#endif+  -- ** Type Prisms+  , _ForallT+  , _AppT+  , _SigT+  , _VarT+  , _ConT+  , _PromotedT+  , _TupleT+  , _UnboxedTupleT+#if MIN_VERSION_template_haskell(2,12,0)+  , _UnboxedSumT+#endif+  , _ArrowT+  , _EqualityT+  , _ListT+  , _PromotedTupleT+  , _PromotedNilT+  , _PromotedConsT+  , _StarT+  , _ConstraintT+  , _LitT+  , _InfixT+  , _UInfixT+  , _ParensT+  , _WildCardT+#if MIN_VERSION_template_haskell(2,15,0)+  , _AppKindT+  , _ImplicitParamT+#endif+#if MIN_VERSION_template_haskell(2,16,0)+  , _ForallVisT+#endif+#if MIN_VERSION_template_haskell(2,17,0)+  , _MulArrowT+#endif+#if MIN_VERSION_template_haskell(2,19,0)+  , _PromotedInfixT+  , _PromotedUInfixT+#endif+#if MIN_VERSION_template_haskell(2,17,0)+  -- ** Specificity Prisms+  , _SpecifiedSpec+  , _InferredSpec+#endif+#if MIN_VERSION_template_haskell(2,21,0)+  -- ** BndrVis Prisms+  , _BndrReq+  , _BndrInvis+#endif+  -- ** TyVarBndr Prisms+  , _PlainTV+  , _KindedTV+  -- ** FamilyResultSig Prisms+  , _NoSig+  , _KindSig+  , _TyVarSig+  -- ** TyLit Prisms+  , _NumTyLit+  , _StrTyLit+#if MIN_VERSION_template_haskell(2,18,0)+  , _CharTyLit+#endif+  -- ** Role Prisms+  , _NominalR+  , _RepresentationalR+  , _PhantomR+  , _InferR+#if MIN_VERSION_template_haskell(2,12,0)+  -- ** DerivStrategy Prisms+  , _StockStrategy+  , _AnyclassStrategy+  , _NewtypeStrategy+#endif+  ) where++import Control.Applicative+import Control.Lens.At+import Control.Lens.Getter+import Control.Lens.Setter+import Control.Lens.Fold+import Control.Lens.Internal.TH+import Control.Lens.Iso (Iso', iso)+import Control.Lens.Lens+import Control.Lens.Prism+import Control.Lens.Tuple+import Control.Lens.Traversal+import qualified Data.Map as Map+import Data.Map (Map)+import Data.Maybe (fromMaybe)+import Data.Monoid+import qualified Data.Set as Set+import Data.Set (Set)+import Data.Set.Lens+import Language.Haskell.TH+import Language.Haskell.TH.Datatype.TyVarBndr+import Language.Haskell.TH.Syntax+import Data.Word+#if MIN_VERSION_template_haskell(2,15,0)+import Data.Foldable as F (foldl')+#endif+#if MIN_VERSION_template_haskell(2,18,0)+import Data.List.NonEmpty (NonEmpty)+#endif+import Prelude++-- | Has a 'Name'+class HasName t where+  -- | Extract (or modify) the 'Name' of something+  name :: Lens' t Name++instance HasName (TyVarBndr_ flag) where+  name = traverseTVName++instance HasName Name where+  name = id++-- | On @template-haskell-2.11.0.0@ or later, if a 'GadtC' or 'RecGadtC' has+-- multiple 'Name's, the leftmost 'Name' will be chosen.+instance HasName Con where+  name f (NormalC n tys)       = (`NormalC` tys) <$> f n+  name f (RecC n tys)          = (`RecC` tys) <$> f n+  name f (InfixC l n r)        = (\n' -> InfixC l n' r) <$> f n+  name f (ForallC bds ctx con) = ForallC bds ctx <$> name f con+  name f (GadtC ns argTys retTy) =+    (\n -> GadtC [n] argTys retTy) <$> f (headGadtConName ns)+  name f (RecGadtC ns argTys retTy) =+    (\n -> RecGadtC [n] argTys retTy) <$> f (headGadtConName ns)++-- @template-haskell@ maintains the invariant that the list of constructor+-- @Name@s in a 'GadtC' or 'RecGadtC' will always be non-empty.+headGadtConName :: [Name] -> Name+headGadtConName conNames =+  case conNames of+    conName:_ -> conName+    [] -> error "headGadtConName: Unexpected empty list of GADT constructor names"++instance HasName Foreign where+  name f (ImportF cc saf str n ty) =+    (\n' -> ImportF cc saf str n' ty) <$> f n+  name f (ExportF cc str n ty) =+    (\n' -> ExportF cc str n' ty) <$> f n++instance HasName RuleBndr where+  name f (RuleVar n) = RuleVar <$> f n+  name f (TypedRuleVar n ty) = (`TypedRuleVar` ty) <$> f n++instance HasName TypeFamilyHead where+  name f (TypeFamilyHead n tvbs frs mia) =+    (\n' -> TypeFamilyHead n' tvbs frs mia) <$> f n++instance HasName InjectivityAnn where+  name f (InjectivityAnn n deps) = (`InjectivityAnn` deps) <$> f n++-- | Contains some amount of `Type`s inside+class HasTypes t where+  -- | Traverse all the types+  types :: Traversal' t Type++instance HasTypes Type where+  types = id++instance HasTypes Con where+  types f (NormalC n t)      = NormalC n <$> traverse (_2 (types f)) t+  types f (RecC n t)         = RecC n <$> traverse (_3 (types f)) t+  types f (InfixC t1 n t2) = InfixC <$> _2 (types f) t1+                                       <*> pure n <*> _2 (types f) t2+  types f (ForallC vb ctx con)    = ForallC vb ctx <$> types f con+  types f (GadtC ns argTys retTy) =+    GadtC    ns <$> traverse (_2 (types f)) argTys <*> types f retTy+  types f (RecGadtC ns argTys retTy) =+    RecGadtC ns <$> traverse (_3 (types f)) argTys <*> types f retTy++instance HasTypes Foreign where+  types f (ImportF cc saf str n t) = ImportF cc saf str n <$> types f t+  types f (ExportF cc     str n t) = ExportF cc     str n <$> types f t++instance HasTypes TySynEqn where+#if MIN_VERSION_template_haskell(2,15,0)+  types f (TySynEqn mtvbs lhs rhs) = TySynEqn <$> traverse (traverse go) mtvbs+                                              <*> types f lhs+                                              <*> types f rhs+    where+      go = traverseTVKind f+#else+  types f (TySynEqn lhss rhs) = TySynEqn <$> traverse (types f) lhss+                                         <*> types f rhs+#endif++instance HasTypes t => HasTypes [t] where+  types = traverse . types++-- | Provides for the extraction of free type variables, and alpha renaming.+class HasTypeVars t where+  -- | When performing substitution into this traversal you're not allowed+  -- to substitute in a name that is bound internally or you'll violate+  -- the 'Traversal' laws, when in doubt generate your names with 'newName'.+  typeVarsEx :: Set Name -> Traversal' t Name++instance HasTypeVars (TyVarBndr_ flag) where+  typeVarsEx s f b+    | s^.contains (b^.name) = pure b+    | otherwise             = name f b++instance HasTypeVars Name where+  typeVarsEx s f n+    | s^.contains n = pure n+    | otherwise     = f n++instance HasTypeVars Type where+  typeVarsEx s f (VarT n)             = VarT <$> typeVarsEx s f n+  typeVarsEx s f (AppT l r)           = AppT <$> typeVarsEx s f l <*> typeVarsEx s f r+  typeVarsEx s f (ForallT bs ctx ty)  = ForallT bs <$> typeVarsEx s' f ctx <*> typeVarsEx s' f ty+       where s' = s `Set.union` setOf typeVars bs+  typeVarsEx _ _ t@ConT{}             = pure t+  typeVarsEx _ _ t@TupleT{}           = pure t+  typeVarsEx _ _ t@ListT{}            = pure t+  typeVarsEx _ _ t@ArrowT{}           = pure t+  typeVarsEx _ _ t@UnboxedTupleT{}    = pure t+  typeVarsEx s f (SigT t k)           = SigT <$> typeVarsEx s f t+                                             <*> typeVarsEx s f k+  typeVarsEx _ _ t@PromotedT{}        = pure t+  typeVarsEx _ _ t@PromotedTupleT{}   = pure t+  typeVarsEx _ _ t@PromotedNilT{}     = pure t+  typeVarsEx _ _ t@PromotedConsT{}    = pure t+  typeVarsEx _ _ t@StarT{}            = pure t+  typeVarsEx _ _ t@ConstraintT{}      = pure t+  typeVarsEx _ _ t@LitT{}             = pure t+  typeVarsEx _ _ t@EqualityT{}        = pure t+  typeVarsEx s f (InfixT  t1 n t2)    = InfixT  <$> typeVarsEx s f t1+                                                <*> pure n+                                                <*> typeVarsEx s f t2+  typeVarsEx s f (UInfixT t1 n t2)    = UInfixT <$> typeVarsEx s f t1+                                                <*> pure n+                                                <*> typeVarsEx s f t2+  typeVarsEx s f (ParensT t)          = ParensT <$> typeVarsEx s f t+  typeVarsEx _ _ t@WildCardT{}        = pure t+#if MIN_VERSION_template_haskell(2,12,0)+  typeVarsEx _ _ t@UnboxedSumT{}      = pure t+#endif+#if MIN_VERSION_template_haskell(2,15,0)+  typeVarsEx s f (AppKindT t k)       = AppKindT <$> typeVarsEx s f t+                                                 <*> typeVarsEx s f k+  typeVarsEx s f (ImplicitParamT n t) = ImplicitParamT n <$> typeVarsEx s f t+#endif+#if MIN_VERSION_template_haskell(2,16,0)+  typeVarsEx s f (ForallVisT bs ty)   = ForallVisT bs <$> typeVarsEx s' f ty+       where s' = s `Set.union` setOf typeVars bs+#endif+#if MIN_VERSION_template_haskell(2,17,0)+  typeVarsEx _ _ t@MulArrowT{}        = pure t+#endif+#if MIN_VERSION_template_haskell(2,19,0)+  typeVarsEx s f (PromotedInfixT  t1 n t2) = PromotedInfixT  <$> typeVarsEx s f t1+                                                             <*> pure n+                                                             <*> typeVarsEx s f t2+  typeVarsEx s f (PromotedUInfixT t1 n t2) = PromotedUInfixT <$> typeVarsEx s f t1+                                                             <*> pure n+                                                             <*> typeVarsEx s f t2+#endif++instance HasTypeVars Con where+  typeVarsEx s f (NormalC n ts) = NormalC n <$> traverseOf (traverse . _2) (typeVarsEx s f) ts+  typeVarsEx s f (RecC n ts) = RecC n <$> traverseOf (traverse . _3) (typeVarsEx s f) ts+  typeVarsEx s f (InfixC l n r) = InfixC <$> g l <*> pure n <*> g r+       where g (i, t) = (,) i <$> typeVarsEx s f t+  typeVarsEx s f (ForallC bs ctx c) = ForallC bs <$> typeVarsEx s' f ctx <*> typeVarsEx s' f c+       where s' = s `Set.union` setOf typeVars bs+  typeVarsEx s f (GadtC ns argTys retTy) =+    GadtC ns <$> traverseOf (traverse . _2) (typeVarsEx s f) argTys+             <*> typeVarsEx s f retTy+  typeVarsEx s f (RecGadtC ns argTys retTy) =+    RecGadtC ns <$> traverseOf (traverse . _3) (typeVarsEx s f) argTys+                <*> typeVarsEx s f retTy++instance HasTypeVars t => HasTypeVars [t] where+  typeVarsEx s = traverse . typeVarsEx s++instance HasTypeVars t => HasTypeVars (Maybe t) where+  typeVarsEx s = traverse . typeVarsEx s++-- | Traverse /free/ type variables+typeVars :: HasTypeVars t => Traversal' t Name+typeVars = typeVarsEx mempty++-- | Substitute using a map of names in for /free/ type variables+substTypeVars :: HasTypeVars t => Map Name Name -> t -> t+substTypeVars m = over typeVars $ \n -> fromMaybe n (m^.at n)++-- | Provides substitution for types+class SubstType t where+  -- | Perform substitution for types+  substType :: Map Name Type -> t -> t++instance SubstType Type where+  substType m t@(VarT n)           = fromMaybe t (m^.at n)+  substType m (ForallT bs ctx ty)  = ForallT bs (substType m' ctx) (substType m' ty)+    where m' = foldrOf typeVars Map.delete m bs+  substType _ t@ConT{}             = t+  substType _ t@TupleT{}           = t+  substType _ t@ListT{}            = t+  substType _ t@ArrowT{}           = t+  substType _ t@UnboxedTupleT{}    = t+  substType m (AppT l r)           = AppT (substType m l) (substType m r)+  substType m (SigT t k)           = SigT (substType m t)+                                          (substType m k)+  substType _ t@PromotedT{}        = t+  substType _ t@PromotedTupleT{}   = t+  substType _ t@PromotedNilT{}     = t+  substType _ t@PromotedConsT{}    = t+  substType _ t@StarT{}            = t+  substType _ t@ConstraintT{}      = t+  substType _ t@LitT{}             = t+  substType _ t@EqualityT{}        = t+  substType m (InfixT  t1 n t2)    = InfixT  (substType m t1) n (substType m t2)+  substType m (UInfixT t1 n t2)    = UInfixT (substType m t1) n (substType m t2)+  substType m (ParensT t)          = ParensT (substType m t)+  substType _ t@WildCardT{}        = t+#if MIN_VERSION_template_haskell(2,12,0)+  substType _ t@UnboxedSumT{}      = t+#endif+#if MIN_VERSION_template_haskell(2,15,0)+  substType m (AppKindT t k)       = AppKindT (substType m t) (substType m k)+  substType m (ImplicitParamT n t) = ImplicitParamT n (substType m t)+#endif+#if MIN_VERSION_template_haskell(2,16,0)+  substType m (ForallVisT bs ty)   = ForallVisT bs (substType m' ty)+    where m' = foldrOf typeVars Map.delete m bs+#endif+#if MIN_VERSION_template_haskell(2,17,0)+  substType _ t@MulArrowT{}        = t+#endif+#if MIN_VERSION_template_haskell(2,19,0)+  substType m (PromotedInfixT  t1 n t2) = PromotedInfixT  (substType m t1) n (substType m t2)+  substType m (PromotedUInfixT t1 n t2) = PromotedUInfixT (substType m t1) n (substType m t2)+#endif++instance SubstType t => SubstType [t] where+  substType = map . substType++-- | Provides a 'Traversal' of the types of each field of a constructor.+conFields :: Traversal' Con BangType+conFields f (NormalC n fs)      = NormalC n <$> traverse f fs+conFields f (RecC n fs)         = RecC n <$> traverse (sansVar f) fs+conFields f (InfixC l n r)      = InfixC <$> f l <*> pure n <*> f r+conFields f (ForallC bds ctx c) = ForallC bds ctx <$> conFields f c+conFields f (GadtC ns argTys retTy) =+  GadtC ns <$> traverse f argTys <*> pure retTy+conFields f (RecGadtC ns argTys retTy) =+  RecGadtC ns <$> traverse (sansVar f) argTys <*> pure retTy++sansVar :: Traversal' VarBangType BangType+sansVar f (fn,s,t) = (\(s', t') -> (fn,s',t')) <$> f (s, t)++-- | 'Traversal' of the types of the /named/ fields of a constructor.+conNamedFields :: Traversal' Con VarBangType+conNamedFields _ c@NormalC{}      = pure c+conNamedFields _ c@InfixC{}       = pure c+conNamedFields f (RecC n fs)      = RecC n <$> traverse f fs+conNamedFields f (ForallC a b fs) = ForallC a b <$> conNamedFields f fs+conNamedFields _ c@GadtC{}        = pure c+conNamedFields f (RecGadtC ns argTys retTy) =+  RecGadtC ns <$> traverse f argTys <*> pure retTy++-- Lenses and Prisms+locFileName :: Lens' Loc String+locFileName = lens loc_filename+            $ \loc fn -> loc { loc_filename = fn }++locPackage :: Lens' Loc String+locPackage = lens loc_package+           $ \loc fn -> loc { loc_package = fn }++locModule :: Lens' Loc String+locModule = lens loc_module+          $ \loc fn -> loc { loc_module = fn }++locStart :: Lens' Loc CharPos+locStart = lens loc_start+         $ \loc fn -> loc { loc_start = fn }++locEnd :: Lens' Loc CharPos+locEnd = lens loc_end+       $ \loc fn -> loc { loc_end = fn }++funDepInputs :: Lens' FunDep [Name]+funDepInputs = lens g s where+   g (FunDep xs _)    = xs+   s (FunDep _ ys) xs = FunDep xs ys++funDepOutputs :: Lens' FunDep [Name]+funDepOutputs = lens g s where+   g (FunDep _ xs) = xs+   s (FunDep ys _) = FunDep ys++fieldExpName :: Lens' FieldExp Name+fieldExpName = _1++fieldExpExpression :: Lens' FieldExp Exp+fieldExpExpression = _2++fieldPatName :: Lens' FieldPat Name+fieldPatName = _1++fieldPatPattern :: Lens' FieldPat Pat+fieldPatPattern = _2++matchPattern :: Lens' Match Pat+matchPattern = lens g s where+   g (Match p _ _)   = p+   s (Match _ x y) p = Match p x y++matchBody :: Lens' Match Body+matchBody = lens g s where+   g (Match _ b _)   = b+   s (Match x _ y) b = Match x b y++matchDeclarations :: Lens' Match [Dec]+matchDeclarations = lens g s where+   g (Match _ _ ds) = ds+   s (Match x y _ ) = Match x y++fixityPrecedence :: Lens' Fixity Int+fixityPrecedence = lens g s where+   g (Fixity i _)   = i+   s (Fixity _ x) i = Fixity i x++fixityDirection :: Lens' Fixity FixityDirection+fixityDirection = lens g s where+   g (Fixity _ d) = d+   s (Fixity i _) = Fixity i++clausePattern :: Lens' Clause [Pat]+clausePattern = lens g s where+   g (Clause ps _ _)    = ps+   s (Clause _  x y) ps = Clause ps x y++clauseBody :: Lens' Clause Body+clauseBody = lens g s where+   g (Clause _ b _)   = b+   s (Clause x _ y) b = Clause x b y++clauseDecs :: Lens' Clause [Dec]+clauseDecs = lens g s where+   g (Clause _ _ ds) = ds+   s (Clause x y _ ) = Clause x y++injectivityAnnOutput :: Lens' InjectivityAnn Name+injectivityAnnOutput = lens g s where+   g (InjectivityAnn o _)   = o+   s (InjectivityAnn _ i) o = InjectivityAnn o i++injectivityAnnInputs :: Lens' InjectivityAnn [Name]+injectivityAnnInputs = lens g s where+   g (InjectivityAnn _ i) = i+   s (InjectivityAnn o _) = InjectivityAnn o++typeFamilyHeadName :: Lens' TypeFamilyHead Name+typeFamilyHeadName = lens g s where+  g (TypeFamilyHead n _    _  _ )   = n+  s (TypeFamilyHead _ tvbs rs ia) n = TypeFamilyHead n tvbs rs ia++typeFamilyHeadTyVarBndrs :: Lens' TypeFamilyHead [TyVarBndrVis]+typeFamilyHeadTyVarBndrs = lens g s where+  g (TypeFamilyHead _ tvbs _  _ )      = tvbs+  s (TypeFamilyHead n _    rs ia) tvbs = TypeFamilyHead n tvbs rs ia++typeFamilyHeadResultSig :: Lens' TypeFamilyHead FamilyResultSig+typeFamilyHeadResultSig = lens g s where+  g (TypeFamilyHead _ _    rs _ )    = rs+  s (TypeFamilyHead n tvbs _  ia) rs = TypeFamilyHead n tvbs rs ia++typeFamilyHeadInjectivityAnn :: Lens' TypeFamilyHead (Maybe InjectivityAnn)+typeFamilyHeadInjectivityAnn = lens g s where+  g (TypeFamilyHead _ _    _  ia) = ia+  s (TypeFamilyHead n tvbs rs _ ) = TypeFamilyHead n tvbs rs++bangSourceUnpackedness :: Lens' Bang SourceUnpackedness+bangSourceUnpackedness = lens g s where+  g (Bang su _ )    = su+  s (Bang _  ss) su = Bang su ss++bangSourceStrictness :: Lens' Bang SourceStrictness+bangSourceStrictness = lens g s where+  g (Bang _  su) = su+  s (Bang ss _ ) = Bang ss++#if MIN_VERSION_template_haskell(2,12,0)+derivClauseStrategy :: Lens' DerivClause (Maybe DerivStrategy)+derivClauseStrategy = lens g s where+  g (DerivClause mds _)     = mds+  s (DerivClause _   c) mds = DerivClause mds c++derivClauseCxt :: Lens' DerivClause Cxt+derivClauseCxt = lens g s where+  g (DerivClause _   c) = c+  s (DerivClause mds _) = DerivClause mds+#endif++_ClassI :: Prism' Info (Dec, [InstanceDec])+_ClassI+  = prism' reviewer remitter+  where+      reviewer (x, y) = ClassI x y+      remitter (ClassI x y) = Just (x, y)+      remitter _ = Nothing++_ClassOpI :: Prism' Info (Name, Type, ParentName)+_ClassOpI+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = ClassOpI x y z+      remitter (ClassOpI x y z) = Just (x, y, z)+      remitter _ = Nothing++_TyConI :: Prism' Info Dec+_TyConI+  = prism' reviewer remitter+  where+      reviewer = TyConI+      remitter (TyConI x) = Just x+      remitter _ = Nothing++_FamilyI :: Prism' Info (Dec, [InstanceDec])+_FamilyI+  = prism' reviewer remitter+  where+      reviewer (x, y) = FamilyI x y+      remitter (FamilyI x y) = Just (x, y)+      remitter _ = Nothing++_PrimTyConI :: Prism' Info (Name, Arity, Unlifted)+_PrimTyConI+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = PrimTyConI x y z+      remitter (PrimTyConI x y z) = Just (x, y, z)+      remitter _ = Nothing++_DataConI :: Prism' Info (Name, Type, ParentName)+_DataConI+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = DataConI x y z+      remitter (DataConI x y z) = Just (x, y, z)+      remitter _ = Nothing++_VarI :: Prism' Info (Name, Type, Maybe Dec)+_VarI+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = VarI x y z+      remitter (VarI x y z) = Just (x, y, z)+      remitter _ = Nothing++_TyVarI :: Prism' Info (Name, Type)+_TyVarI+  = prism' reviewer remitter+  where+      reviewer (x, y) = TyVarI x y+      remitter (TyVarI x y) = Just (x, y)+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,12,0)+_PatSynI :: Prism' Info (Name, PatSynType)+_PatSynI+  = prism' reviewer remitter+  where+      reviewer (x, y) = PatSynI x y+      remitter (PatSynI x y) = Just (x, y)+      remitter _ = Nothing+#endif++_FunD :: Prism' Dec (Name, [Clause])+_FunD+  = prism' reviewer remitter+  where+      reviewer (x, y) = FunD x y+      remitter (FunD x y) = Just (x,y)+      remitter _ = Nothing++_ValD :: Prism' Dec (Pat, Body, [Dec])+_ValD+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = ValD x y z+      remitter (ValD x y z) = Just (x, y, z)+      remitter _ = Nothing++_TySynD :: Prism' Dec (Name, [TyVarBndrVis], Type)+_TySynD+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = TySynD x y z+      remitter (TySynD x y z) = Just (x, y, z)+      remitter _ = Nothing++_ClassD :: Prism' Dec (Cxt, Name, [TyVarBndrVis], [FunDep], [Dec])+_ClassD+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w, u) = ClassD x y z w u+      remitter (ClassD x y z w u) = Just (x, y, z, w, u)+      remitter _ = Nothing++_InstanceD :: Prism' Dec (Maybe Overlap, Cxt, Type, [Dec])+_InstanceD+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w) = InstanceD x y z w+      remitter (InstanceD x y z w) = Just (x, y, z, w)+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,22,0)+_NoNamespaceSpecifier :: Prism' NamespaceSpecifier ()+_NoNamespaceSpecifier+  = prism' reviewer remitter+  where+      reviewer () = NoNamespaceSpecifier+      remitter NoNamespaceSpecifier = Just ()+      remitter _ = Nothing++_TypeNamespaceSpecifier :: Prism' NamespaceSpecifier ()+_TypeNamespaceSpecifier+  = prism' reviewer remitter+  where+      reviewer () = TypeNamespaceSpecifier+      remitter TypeNamespaceSpecifier = Just ()+      remitter _ = Nothing++_DataNamespaceSpecifier :: Prism' NamespaceSpecifier ()+_DataNamespaceSpecifier+  = prism' reviewer remitter+  where+      reviewer () = DataNamespaceSpecifier+      remitter DataNamespaceSpecifier = Just ()+      remitter _ = Nothing+#endif++_Overlappable  :: Prism' Overlap  ()+_Overlappable  = prism' reviewer remitter+  where+      reviewer () = Overlappable+      remitter Overlappable = Just  ()+      remitter _ = Nothing++_Overlapping :: Prism' Overlap ()+_Overlapping = prism' reviewer remitter+  where+      reviewer () = Overlapping+      remitter Overlapping = Just ()+      remitter _ = Nothing++_Overlaps ::  Prism' Overlap  ()+_Overlaps =  prism' reviewer remitter+  where+      reviewer () =  Overlaps+      remitter Overlaps = Just ()+      remitter _ = Nothing++_Incoherent  :: Prism' Overlap ()+_Incoherent  = prism' reviewer remitter+  where+      reviewer () = Incoherent+      remitter Incoherent = Just ()+      remitter _ = Nothing++_SigD :: Prism' Dec (Name, Type)+_SigD+  = prism' reviewer remitter+  where+      reviewer (x, y) = SigD x y+      remitter (SigD x y) = Just (x, y)+      remitter _ = Nothing++_ForeignD :: Prism' Dec Foreign+_ForeignD+  = prism' reviewer remitter+  where+      reviewer = ForeignD+      remitter (ForeignD x) = Just x+      remitter _ = Nothing++-- |+-- @+-- _InfixD :: 'Prism'' 'Dec' ('Fixity', 'NamespaceSpecifier', 'Name') -- template-haskell-2.22++-- _InfixD :: 'Prism'' 'Dec' ('Fixity', 'Name')                     -- Earlier versions+-- @+#if MIN_VERSION_template_haskell(2,22,0)+_InfixD :: Prism' Dec (Fixity, NamespaceSpecifier, Name)+_InfixD+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = InfixD x y z+      remitter (InfixD x y z) = Just (x, y, z)+      remitter _ = Nothing+#else+_InfixD :: Prism' Dec (Fixity, Name)+_InfixD+  = prism' reviewer remitter+  where+      reviewer (x, y) = InfixD x y+      remitter (InfixD x y) = Just (x, y)+      remitter _ = Nothing+#endif++_PragmaD :: Prism' Dec Pragma+_PragmaD+  = prism' reviewer remitter+  where+      reviewer = PragmaD+      remitter (PragmaD x) = Just x+      remitter _ = Nothing++-- |+-- @+-- _TySynInstD :: 'Prism'' 'Dec' 'TySynEqn'             -- template-haskell-2.15++-- _TySynInstD :: 'Prism'' 'Dec' ('Name', 'TySynEqn')     -- template-haskell-2.9 through 2.14+-- _TySynInstD :: 'Prism'' 'Dec' ('Name', ['Type'], 'Type') -- Earlier versions+-- @+#if MIN_VERSION_template_haskell(2,15,0)+_TySynInstD :: Prism' Dec TySynEqn+_TySynInstD+  = prism' reviewer remitter+  where+      reviewer = TySynInstD+      remitter (TySynInstD x) = Just x+      remitter _ = Nothing+#else+_TySynInstD :: Prism' Dec (Name, TySynEqn)+_TySynInstD+  = prism' reviewer remitter+  where+      reviewer (x, y) = TySynInstD x y+      remitter (TySynInstD x y) = Just (x, y)+      remitter _ = Nothing+#endif++_RoleAnnotD :: Prism' Dec (Name, [Role])+_RoleAnnotD+  = prism' reviewer remitter+  where+      reviewer (x, y) = RoleAnnotD x y+      remitter (RoleAnnotD x y) = Just (x, y)+      remitter _ = Nothing++-- |+-- @+-- _StandaloneDerivD :: 'Prism'' 'Dec' ('Maybe' 'DerivStrategy', 'Cxt', 'Type') -- template-haskell-2.12++-- _StandaloneDerivD :: 'Prism'' 'Dec'                      ('Cxt', 'Type') -- Earlier versions+-- @+#if MIN_VERSION_template_haskell(2,12,0)+_StandaloneDerivD :: Prism' Dec (Maybe DerivStrategy, Cxt, Type)+_StandaloneDerivD+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = StandaloneDerivD x y z+      remitter (StandaloneDerivD x y z) = Just (x, y, z)+      remitter _ = Nothing+#else+_StandaloneDerivD :: Prism' Dec (Cxt, Type)+_StandaloneDerivD+  = prism' reviewer remitter+  where+      reviewer (x, y) = StandaloneDerivD x y+      remitter (StandaloneDerivD x y) = Just (x, y)+      remitter _ = Nothing+#endif++_DefaultSigD :: Prism' Dec (Name, Type)+_DefaultSigD+  = prism' reviewer remitter+  where+      reviewer (x, y) = DefaultSigD x y+      remitter (DefaultSigD x y) = Just (x, y)+      remitter _ = Nothing++# if MIN_VERSION_template_haskell(2,12,0)+type DataPrism' tys cons = Prism' Dec (Cxt, Name, tys, Maybe Kind, cons, [DerivClause])+# else+type DataPrism' tys cons = Prism' Dec (Cxt, Name, tys, Maybe Kind, cons, Cxt)+# endif++-- |+-- @+-- _DataInstD :: 'Prism'' 'Dec' ('Cxt', 'Maybe' ['TyVarBndrUnit'], 'Type', 'Maybe' 'Kind', ['Con'], ['DerivClause']) -- template-haskell-2.15++-- _DataInstD :: 'Prism'' 'Dec' ('Cxt', 'Name', ['Type'],                'Maybe' 'Kind', ['Con'], ['DerivClause']) -- template-haskell-2.12 through 2.14+-- _DataInstD :: 'Prism'' 'Dec' ('Cxt', 'Name', ['Type'],                'Maybe' 'Kind', ['Con'], 'Cxt')           -- Earlier versions+-- @+#if MIN_VERSION_template_haskell(2,15,0)+_DataInstD :: Prism' Dec (Cxt, Maybe [TyVarBndrUnit], Type, Maybe Kind, [Con], [DerivClause])+_DataInstD+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w, u, v) = DataInstD x y z w u v+      remitter (DataInstD x y z w u v) = Just (x, y, z, w, u, v)+      remitter _ = Nothing+#else+_DataInstD :: DataPrism' [Type] [Con]+_DataInstD+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w, u, v) = DataInstD x y z w u v+      remitter (DataInstD x y z w u v) = Just (x, y, z, w, u, v)+      remitter _ = Nothing+#endif++-- |+-- @+-- _NewtypeInstD :: 'Prism'' 'Dec' ('Cxt', 'Maybe' ['TyVarBndrUnit'], 'Type', 'Maybe' 'Kind', 'Con', ['DerivClause']) -- template-haskell-2.15++-- _NewtypeInstD :: 'Prism'' 'Dec' ('Cxt', 'Name', ['Type'],                'Maybe' 'Kind', 'Con', ['DerivClause']) -- template-haskell-2.12 through 2.14+-- _NewtypeInstD :: 'Prism'' 'Dec' ('Cxt', 'Name', ['Type'],                'Maybe' 'Kind', 'Con', 'Cxt')           -- Earlier versions+-- @+#if MIN_VERSION_template_haskell(2,15,0)+_NewtypeInstD :: Prism' Dec (Cxt, Maybe [TyVarBndrUnit], Type, Maybe Kind, Con, [DerivClause])+_NewtypeInstD+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w, u, v) = NewtypeInstD x y z w u v+      remitter (NewtypeInstD x y z w u v) = Just (x, y, z, w, u, v)+      remitter _ = Nothing+#else+_NewtypeInstD :: DataPrism' [Type] Con+_NewtypeInstD+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w, u, v) = NewtypeInstD x y z w u v+      remitter (NewtypeInstD x y z w u v) = Just (x, y, z, w, u, v)+      remitter _ = Nothing+#endif++_ClosedTypeFamilyD :: Prism' Dec (TypeFamilyHead, [TySynEqn])+_ClosedTypeFamilyD+  = prism' reviewer remitter+  where+      reviewer (x, y) = ClosedTypeFamilyD x y+      remitter (ClosedTypeFamilyD x y) = Just (x, y)+      remitter _ = Nothing++-- |+-- @+-- _DataD :: 'Prism'' 'Dec' ('Cxt', 'Name', ['TyVarBndrUnit'], 'Maybe' 'Kind', ['Con'], ['DerivClause']) -- template-haskell-2.12++-- _DataD :: 'Prism'' 'Dec' ('Cxt', 'Name', ['Type'],          'Maybe' 'Kind', ['Con'], 'Cxt')           -- Earlier versions+-- @+_DataD :: DataPrism' [TyVarBndrVis] [Con]+_DataD+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w, u, v) = DataD x y z w u v+      remitter (DataD x y z w u v) = Just (x, y, z, w, u, v)+      remitter _ = Nothing++-- |+-- @+-- _NewtypeD :: 'Prism'' 'Dec' ('Cxt', 'Name', ['TyVarBndrUnit'], 'Maybe' 'Kind', 'Con', ['DerivClause']) -- template-haskell-2.12++-- _NewtypeD :: 'Prism'' 'Dec' ('Cxt', 'Name', ['Type'],          'Maybe' 'Kind', 'Con', 'Cxt')           -- Earlier versions+-- @+_NewtypeD :: DataPrism' [TyVarBndrVis] Con+_NewtypeD+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w, u, v) = NewtypeD x y z w u v+      remitter (NewtypeD x y z w u v) = Just (x, y, z, w, u, v)+      remitter _ = Nothing++_DataFamilyD :: Prism' Dec (Name, [TyVarBndrVis], Maybe Kind)+_DataFamilyD+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = DataFamilyD x y z+      remitter (DataFamilyD x y z) = Just (x, y, z)+      remitter _ = Nothing++_OpenTypeFamilyD :: Prism' Dec TypeFamilyHead+_OpenTypeFamilyD+  = prism' reviewer remitter+  where+      reviewer = OpenTypeFamilyD+      remitter (OpenTypeFamilyD x) = Just x+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,12,0)+_PatSynD :: Prism' Dec (Name, PatSynArgs, PatSynDir, Pat)+_PatSynD+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w) = PatSynD x y z w+      remitter (PatSynD x y z w) = Just (x, y, z, w)+      remitter _ = Nothing++_PatSynSigD :: Prism' Dec (Name, PatSynType)+_PatSynSigD+  = prism' reviewer remitter+  where+      reviewer (x, y) = PatSynSigD x y+      remitter (PatSynSigD x y) = Just (x, y)+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,15,0)+_ImplicitParamBindD :: Prism' Dec (String, Exp)+_ImplicitParamBindD+  = prism' reviewer remitter+  where+      reviewer (x, y) = ImplicitParamBindD x y+      remitter (ImplicitParamBindD x y) = Just (x, y)+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,19,0)+_DefaultD :: Prism' Dec [Type]+_DefaultD+  = prism' reviewer remitter+  where+      reviewer = DefaultD+      remitter (DefaultD x) = Just x+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,20,0)+_TypeDataD :: Prism' Dec (Name, [TyVarBndrVis], Maybe Kind, [Con])+_TypeDataD+  = prism' reviewer remitter+  where+      reviewer (x, y, z, u) = TypeDataD x y z u+      remitter (TypeDataD x y z u) = Just (x, y, z, u)+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,12,0)+_Unidir :: Prism' PatSynDir ()+_Unidir+  = prism' reviewer remitter+  where+      reviewer () = Unidir+      remitter Unidir = Just ()+      remitter _ = Nothing++_ImplBidir :: Prism' PatSynDir ()+_ImplBidir+  = prism' reviewer remitter+  where+      reviewer () = ImplBidir+      remitter ImplBidir = Just ()+      remitter _ = Nothing++_ExplBidir :: Prism' PatSynDir [Clause]+_ExplBidir+  = prism' reviewer remitter+  where+      reviewer = ExplBidir+      remitter (ExplBidir x) = Just x+      remitter _ = Nothing++_PrefixPatSyn :: Prism' PatSynArgs [Name]+_PrefixPatSyn+  = prism' reviewer remitter+  where+      reviewer = PrefixPatSyn+      remitter (PrefixPatSyn x) = Just x+      remitter _ = Nothing++_InfixPatSyn :: Prism' PatSynArgs (Name, Name)+_InfixPatSyn+  = prism' reviewer remitter+  where+      reviewer (x, y) = InfixPatSyn x y+      remitter (InfixPatSyn x y) = Just (x, y)+      remitter _ = Nothing++_RecordPatSyn :: Prism' PatSynArgs [Name]+_RecordPatSyn+  = prism' reviewer remitter+  where+      reviewer = RecordPatSyn+      remitter (RecordPatSyn x) = Just x+      remitter _ = Nothing+#endif++_NormalC :: Prism' Con (Name, [BangType])+_NormalC+  = prism' reviewer remitter+  where+      reviewer (x, y) = NormalC x y+      remitter (NormalC x y) = Just (x, y)+      remitter _ = Nothing++_RecC :: Prism' Con (Name, [VarBangType])+_RecC+  = prism' reviewer remitter+  where+      reviewer (x, y) = RecC x y+      remitter (RecC x y) = Just (x, y)+      remitter _ = Nothing++_InfixC :: Prism' Con (BangType, Name, BangType  )+_InfixC+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = InfixC x y z+      remitter (InfixC x y z) = Just (x, y, z)+      remitter _ = Nothing++_ForallC :: Prism' Con ([TyVarBndrSpec], Cxt, Con)+_ForallC+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = ForallC x y z+      remitter (ForallC x y z) = Just (x, y, z)+      remitter _ = Nothing++_GadtC :: Prism' Con ([Name], [BangType], Type)+_GadtC+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = GadtC x y z+      remitter (GadtC x y z) = Just (x, y, z)+      remitter _ = Nothing++_RecGadtC :: Prism' Con ([Name], [VarBangType], Type)+_RecGadtC+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = RecGadtC x y z+      remitter (RecGadtC x y z) = Just (x, y, z)+      remitter _ = Nothing++_NoSourceUnpackedness :: Prism' SourceUnpackedness ()+_NoSourceUnpackedness+  = prism' reviewer remitter+  where+      reviewer () = NoSourceUnpackedness+      remitter NoSourceUnpackedness = Just ()+      remitter _ = Nothing++_SourceNoUnpack :: Prism' SourceUnpackedness ()+_SourceNoUnpack+  = prism' reviewer remitter+  where+      reviewer () = SourceNoUnpack+      remitter SourceNoUnpack = Just ()+      remitter _ = Nothing++_SourceUnpack :: Prism' SourceUnpackedness ()+_SourceUnpack+  = prism' reviewer remitter+  where+      reviewer () = SourceUnpack+      remitter SourceUnpack = Just ()+      remitter _ = Nothing++_NoSourceStrictness :: Prism' SourceStrictness ()+_NoSourceStrictness+  = prism' reviewer remitter+  where+      reviewer () = NoSourceStrictness+      remitter NoSourceStrictness = Just ()+      remitter _ = Nothing++_SourceLazy :: Prism' SourceStrictness ()+_SourceLazy+  = prism' reviewer remitter+  where+      reviewer () = SourceLazy+      remitter SourceLazy = Just ()+      remitter _ = Nothing++_SourceStrict :: Prism' SourceStrictness ()+_SourceStrict+  = prism' reviewer remitter+  where+      reviewer () = SourceStrict+      remitter SourceStrict = Just ()+      remitter _ = Nothing++_DecidedLazy :: Prism' DecidedStrictness ()+_DecidedLazy+  = prism' reviewer remitter+  where+      reviewer () = DecidedLazy+      remitter DecidedLazy = Just ()+      remitter _ = Nothing++_DecidedStrict :: Prism' DecidedStrictness ()+_DecidedStrict+  = prism' reviewer remitter+  where+      reviewer () = DecidedStrict+      remitter DecidedStrict = Just ()+      remitter _ = Nothing++_DecidedUnpack :: Prism' DecidedStrictness ()+_DecidedUnpack+  = prism' reviewer remitter+  where+      reviewer () = DecidedUnpack+      remitter DecidedUnpack = Just ()+      remitter _ = Nothing++_ImportF :: Prism' Foreign (Callconv, Safety, String, Name, Type)+_ImportF+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w, u) = ImportF x y z w u+      remitter (ImportF x y z w u) = Just (x,y,z,w,u)+      remitter _ = Nothing++_ExportF :: Prism' Foreign (Callconv, String, Name, Type)+_ExportF+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w) = ExportF x y z w+      remitter (ExportF x y z w) = Just (x, y, z, w)+      remitter _ = Nothing++_CCall :: Prism' Callconv ()+_CCall+  = prism' reviewer remitter+  where+      reviewer () = CCall+      remitter CCall = Just ()+      remitter _ = Nothing++_StdCall :: Prism' Callconv ()+_StdCall+  = prism' reviewer remitter+  where+      reviewer () = StdCall+      remitter StdCall = Just ()+      remitter _ = Nothing++_CApi :: Prism' Callconv ()+_CApi+  = prism' reviewer remitter+  where+      reviewer () = CApi+      remitter CApi = Just ()+      remitter _ = Nothing++_Prim :: Prism' Callconv ()+_Prim+  = prism' reviewer remitter+  where+      reviewer () = Prim+      remitter Prim = Just ()+      remitter _ = Nothing++_JavaScript :: Prism' Callconv ()+_JavaScript+  = prism' reviewer remitter+  where+      reviewer () = JavaScript+      remitter JavaScript = Just ()+      remitter _ = Nothing++_Unsafe :: Prism' Safety ()+_Unsafe+  = prism' reviewer remitter+  where+      reviewer () = Unsafe+      remitter Unsafe = Just ()+      remitter _ = Nothing++_Safe :: Prism' Safety ()+_Safe+  = prism' reviewer remitter+  where+      reviewer () = Safe+      remitter Safe = Just ()+      remitter _ = Nothing++_Interruptible :: Prism' Safety ()+_Interruptible+  = prism' reviewer remitter+  where+      reviewer () = Interruptible+      remitter Interruptible = Just ()+      remitter _ = Nothing++_InlineP :: Prism' Pragma (Name, Inline, RuleMatch, Phases)+_InlineP+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w) = InlineP x y z w+      remitter (InlineP x y z w) = Just (x, y, z, w)+      remitter _ = Nothing++_SpecialiseP :: Prism' Pragma (Name, Type, Maybe Inline, Phases)+_SpecialiseP+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w) = SpecialiseP x y z w+      remitter (SpecialiseP x y z w) = Just (x, y, z, w)+      remitter _ = Nothing++-- TODO add lenses for InlineSpec++_SpecialiseInstP :: Prism' Pragma Type+_SpecialiseInstP+  = prism' reviewer remitter+  where+      reviewer = SpecialiseInstP+      remitter (SpecialiseInstP x) = Just x+      remitter _ = Nothing++-- |+-- @+-- _RuleP :: 'Prism'' 'Pragma' ('String', 'Maybe' ['TyVarBndrUnit'], ['RuleBndr'], 'Exp', 'Exp', 'Phases') -- template-haskell-2.15++-- _RuleP :: 'Prism'' 'Pragma' ('String',                        ['RuleBndr'], 'Exp', 'Exp', 'Phases') -- Earlier versions+-- @+#if MIN_VERSION_template_haskell(2,15,0)+_RuleP :: Prism' Pragma (String, Maybe [TyVarBndrUnit], [RuleBndr], Exp, Exp, Phases)+_RuleP+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w, u, v) = RuleP x y z w u v+      remitter (RuleP x y z w u v) = Just (x, y, z, w, u, v)+      remitter _ = Nothing+#else+_RuleP :: Prism' Pragma (String, [RuleBndr], Exp, Exp, Phases)+_RuleP+  = prism' reviewer remitter+  where+      reviewer (x, y, z, w, u) = RuleP x y z w u+      remitter (RuleP x y z w u) = Just (x, y, z, w, u)+      remitter _ = Nothing+#endif++_AnnP :: Prism' Pragma (AnnTarget, Exp)+_AnnP+  = prism' reviewer remitter+  where+      reviewer (x, y) = AnnP x y+      remitter (AnnP x y) = Just (x, y)+      remitter _ = Nothing++_LineP :: Prism' Pragma (Int, String)+_LineP+  = prism' reviewer remitter+  where+      reviewer (x, y) = LineP x y+      remitter (LineP x y) = Just (x, y)+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,12,0)+_CompleteP :: Prism' Pragma ([Name], Maybe Name)+_CompleteP+  = prism' reviewer remitter+  where+      reviewer (x, y) = CompleteP x y+      remitter (CompleteP x y) = Just (x, y)+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,19,0)+_OpaqueP :: Prism' Pragma Name+_OpaqueP+  = prism' reviewer remitter+  where+      reviewer = OpaqueP+      remitter (OpaqueP x) = Just x+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,22,0)+_SCCP :: Prism' Pragma (Name, Maybe String)+_SCCP+  = prism' reviewer remitter+  where+      reviewer (x, y) = SCCP x y+      remitter (SCCP x y) = Just (x, y)+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,24,0)+_SpecialiseEP :: Prism' Pragma (Maybe [TyVarBndr ()], [RuleBndr], Exp, Maybe Inline, Phases)+_SpecialiseEP+  = prism' reviewer remitter+  where+    reviewer (x, y, z, w, u) = SpecialiseEP x y z w u+    remitter (SpecialiseEP x y z w u) = Just (x, y, z, w, u)+    remitter _ = Nothing+#endif++_NoInline :: Prism' Inline ()+_NoInline+  = prism' reviewer remitter+  where+      reviewer () = NoInline+      remitter NoInline = Just ()+      remitter _ = Nothing++_Inline :: Prism' Inline ()+_Inline+  = prism' reviewer remitter+  where+      reviewer () = Inline+      remitter Inline = Just ()+      remitter _ = Nothing++_Inlinable :: Prism' Inline ()+_Inlinable+  = prism' reviewer remitter+  where+      reviewer () = Inlinable+      remitter Inlinable = Just ()+      remitter _ = Nothing++_ConLike :: Prism' RuleMatch ()+_ConLike+  = prism' reviewer remitter+  where+      reviewer () = ConLike+      remitter ConLike = Just ()+      remitter _ = Nothing++_FunLike :: Prism' RuleMatch ()+_FunLike+  = prism' reviewer remitter+  where+      reviewer () = FunLike+      remitter FunLike = Just ()+      remitter _ = Nothing++_AllPhases :: Prism' Phases ()+_AllPhases+  = prism' reviewer remitter+  where+      reviewer () = AllPhases+      remitter AllPhases = Just ()+      remitter _ = Nothing++_FromPhase :: Prism' Phases Int+_FromPhase+  = prism' reviewer remitter+  where+      reviewer = FromPhase+      remitter (FromPhase x) = Just x+      remitter _ = Nothing++_BeforePhase :: Prism' Phases Int+_BeforePhase+  = prism' reviewer remitter+  where+      reviewer = BeforePhase+      remitter (BeforePhase x) = Just x+      remitter _ = Nothing++_RuleVar :: Prism' RuleBndr Name+_RuleVar+  = prism' reviewer remitter+  where+      reviewer = RuleVar+      remitter (RuleVar x) = Just x+      remitter _ = Nothing++_TypedRuleVar :: Prism' RuleBndr (Name, Type)+_TypedRuleVar+  = prism' reviewer remitter+  where+      reviewer (x, y) = TypedRuleVar x y+      remitter (TypedRuleVar x y) = Just (x, y)+      remitter _ = Nothing++_ModuleAnnotation :: Prism' AnnTarget ()+_ModuleAnnotation+  = prism' reviewer remitter+  where+      reviewer () = ModuleAnnotation+      remitter ModuleAnnotation = Just ()+      remitter _ = Nothing++_TypeAnnotation :: Prism' AnnTarget Name+_TypeAnnotation+  = prism' reviewer remitter+  where+      reviewer = TypeAnnotation+      remitter (TypeAnnotation x) = Just x+      remitter _ = Nothing++_ValueAnnotation :: Prism' AnnTarget Name+_ValueAnnotation+  = prism' reviewer remitter+  where+      reviewer = ValueAnnotation+      remitter (ValueAnnotation x) = Just x+      remitter _ = Nothing++_FunDep :: Iso' FunDep ([Name], [Name])+_FunDep+  = iso remitter reviewer+  where+      reviewer (x, y) = FunDep x y+      remitter (FunDep x y) = (x, y)++#if !(MIN_VERSION_template_haskell(2,13,0))+_TypeFam :: Prism' FamFlavour ()+_TypeFam+  = prism' reviewer remitter+  where+      reviewer () = TypeFam+      remitter TypeFam = Just ()+      remitter _ = Nothing++_DataFam :: Prism' FamFlavour ()+_DataFam+  = prism' reviewer remitter+  where+      reviewer () = DataFam+      remitter DataFam = Just ()+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,15,0)+tySynEqnLHS :: Lens' TySynEqn Type+tySynEqnLHS = lens g s where+   g (TySynEqn _     lhs _)       = lhs+   s (TySynEqn mtvbs _   rhs) lhs = TySynEqn mtvbs lhs rhs++tySynEqnPatterns :: Lens' TySynEqn [Type]+tySynEqnPatterns = lens g s where+   g (TySynEqn _     lhs _) = pats+     where (_n, pats) = unfoldType lhs+   s (TySynEqn mtvbs lhs rhs) pats = TySynEqn mtvbs (F.foldl' AppT n pats) rhs+     where (n, _pats) = unfoldType lhs++tySynEqnResult :: Lens' TySynEqn Type+tySynEqnResult = lens g s where+   g (TySynEqn _     _   rhs) = rhs+   s (TySynEqn mtvbs lhs _)   = TySynEqn mtvbs lhs+#else+tySynEqnPatterns :: Lens' TySynEqn [Type]+tySynEqnPatterns = lens g s where+   g (TySynEqn xs _)    = xs+   s (TySynEqn _  y) xs = TySynEqn xs y++tySynEqnResult :: Lens' TySynEqn Type+tySynEqnResult = lens g s where+   g (TySynEqn _  x) = x+   s (TySynEqn xs _) = TySynEqn xs+#endif++_InfixL :: Prism' FixityDirection ()+_InfixL+  = prism' reviewer remitter+  where+      reviewer () = InfixL+      remitter InfixL = Just ()+      remitter _ = Nothing++_InfixR :: Prism' FixityDirection ()+_InfixR+  = prism' reviewer remitter+  where+      reviewer () = InfixR+      remitter InfixR = Just ()+      remitter _ = Nothing++_InfixN :: Prism' FixityDirection ()+_InfixN+  = prism' reviewer remitter+  where+      reviewer () = InfixN+      remitter InfixN = Just ()+      remitter _ = Nothing++_VarE :: Prism' Exp Name+_VarE+  = prism' reviewer remitter+  where+      reviewer = VarE+      remitter (VarE x) = Just x+      remitter _ = Nothing++_ConE :: Prism' Exp Name+_ConE+  = prism' reviewer remitter+  where+      reviewer = ConE+      remitter (ConE x) = Just x+      remitter _ = Nothing++_LitE :: Prism' Exp Lit+_LitE+  = prism' reviewer remitter+  where+      reviewer = LitE+      remitter (LitE x) = Just x+      remitter _ = Nothing++_AppE :: Prism' Exp (Exp, Exp)+_AppE+  = prism' reviewer remitter+  where+      reviewer (x, y) = AppE x y+      remitter (AppE x y) = Just (x, y)+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,12,0)+_AppTypeE :: Prism' Exp (Exp, Type)+_AppTypeE+  = prism' reviewer remitter+  where+      reviewer (x, y) = AppTypeE x y+      remitter (AppTypeE x y) = Just (x, y)+      remitter _ = Nothing+#endif++_InfixE :: Prism' Exp (Maybe Exp, Exp, Maybe Exp)+_InfixE+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = InfixE x y z+      remitter (InfixE x y z) = Just (x, y, z)+      remitter _ = Nothing++_UInfixE :: Prism' Exp (Exp, Exp, Exp)+_UInfixE+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = UInfixE x y z+      remitter (UInfixE x y z) = Just (x, y, z)+      remitter _ = Nothing++_ParensE :: Prism' Exp Exp+_ParensE+  = prism' reviewer remitter+  where+      reviewer = ParensE+      remitter (ParensE x) = Just x+      remitter _ = Nothing++_LamE :: Prism' Exp ([Pat], Exp)+_LamE+  = prism' reviewer remitter+  where+      reviewer (x, y) = LamE x y+      remitter (LamE x y) = Just (x, y)+      remitter _ = Nothing++_LamCaseE :: Prism' Exp [Match]+_LamCaseE+  = prism' reviewer remitter+  where+      reviewer = LamCaseE+      remitter (LamCaseE x) = Just x+      remitter _ = Nothing++-- |+-- @+-- _TupE :: 'Prism'' 'Exp' ['Maybe' 'Exp'] -- template-haskell-2.16++-- _TupE :: 'Prism'' 'Exp' ['Exp']       -- Earlier versions+-- @+#if MIN_VERSION_template_haskell(2,16,0)+_TupE :: Prism' Exp [Maybe Exp]+#else+_TupE :: Prism' Exp [Exp]+#endif+_TupE+  = prism' reviewer remitter+  where+      reviewer = TupE+      remitter (TupE x) = Just x+      remitter _ = Nothing++-- |+-- @+-- _UnboxedTupE :: 'Prism'' 'Exp' ['Maybe' 'Exp'] -- template-haskell-2.16++-- _UnboxedTupE :: 'Prism'' 'Exp' ['Exp']       -- Earlier versions+-- @+#if MIN_VERSION_template_haskell(2,16,0)+_UnboxedTupE :: Prism' Exp [Maybe Exp]+#else+_UnboxedTupE :: Prism' Exp [Exp]+#endif+_UnboxedTupE+  = prism' reviewer remitter+  where+      reviewer = UnboxedTupE+      remitter (UnboxedTupE x) = Just x+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,12,0)+_UnboxedSumE :: Prism' Exp (Exp, SumAlt, SumArity)+_UnboxedSumE+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = UnboxedSumE x y z+      remitter (UnboxedSumE x y z) = Just (x, y, z)+      remitter _ = Nothing+#endif++_CondE :: Prism' Exp (Exp, Exp, Exp)+_CondE+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = CondE x y z+      remitter (CondE x y z) = Just (x, y, z)+      remitter _ = Nothing++_MultiIfE :: Prism' Exp [(Guard, Exp)]+_MultiIfE+  = prism' reviewer remitter+  where+      reviewer = MultiIfE+      remitter (MultiIfE x) = Just x+      remitter _ = Nothing++_LetE :: Prism' Exp ([Dec], Exp)+_LetE+  = prism' reviewer remitter+  where+      reviewer (x, y) = LetE x y+      remitter (LetE x y) = Just (x, y)+      remitter _ = Nothing++_CaseE :: Prism' Exp (Exp, [Match])+_CaseE+  = prism' reviewer remitter+  where+      reviewer (x, y) = CaseE x y+      remitter (CaseE x y) = Just (x, y)+      remitter _ = Nothing++-- |+-- @+-- _DoE :: 'Prism'' 'Exp' ('Maybe' 'ModName', ['Stmt']) -- template-haskell-2.17++-- _DoE :: 'Prism'' 'Exp' ['Stmt']                  -- Earlier versions+-- @+# if MIN_VERSION_template_haskell(2,17,0)+_DoE :: Prism' Exp (Maybe ModName, [Stmt])+_DoE+  = prism' reviewer remitter+  where+      reviewer (x, y) = DoE x y+      remitter (DoE x y) = Just (x, y)+      remitter _ = Nothing+# else+_DoE :: Prism' Exp [Stmt]+_DoE+  = prism' reviewer remitter+  where+      reviewer = DoE+      remitter (DoE x) = Just x+      remitter _ = Nothing+# endif++_CompE :: Prism' Exp [Stmt]+_CompE+  = prism' reviewer remitter+  where+      reviewer = CompE+      remitter (CompE x) = Just x+      remitter _ = Nothing++_ArithSeqE :: Prism' Exp Range+_ArithSeqE+  = prism' reviewer remitter+  where+      reviewer = ArithSeqE+      remitter (ArithSeqE x) = Just x+      remitter _ = Nothing++_ListE :: Prism' Exp [Exp]+_ListE+  = prism' reviewer remitter+  where+      reviewer = ListE+      remitter (ListE x) = Just x+      remitter _ = Nothing++_SigE :: Prism' Exp (Exp, Type)+_SigE+  = prism' reviewer remitter+  where+      reviewer (x, y) = SigE x y+      remitter (SigE x y) = Just (x, y)+      remitter _ = Nothing++_RecConE :: Prism' Exp (Name, [FieldExp])+_RecConE+  = prism' reviewer remitter+  where+      reviewer (x, y) = RecConE x y+      remitter (RecConE x y) = Just (x, y)+      remitter _ = Nothing++_RecUpdE :: Prism' Exp (Exp, [FieldExp])+_RecUpdE+  = prism' reviewer remitter+  where+      reviewer (x, y) = RecUpdE x y+      remitter (RecUpdE x y) = Just (x, y)+      remitter _ = Nothing++_StaticE :: Prism' Exp Exp+_StaticE+  = prism' reviewer remitter+  where+      reviewer = StaticE+      remitter (StaticE x) = Just x+      remitter _ = Nothing++_UnboundVarE :: Prism' Exp Name+_UnboundVarE+  = prism' reviewer remitter+  where+      reviewer = UnboundVarE+      remitter (UnboundVarE x) = Just x+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,13,0)+_LabelE :: Prism' Exp String+_LabelE+  = prism' reviewer remitter+  where+      reviewer = LabelE+      remitter (LabelE x) = Just x+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,15,0)+-- |+-- @+-- _MDoE :: 'Prism'' 'Exp' ('Maybe' 'ModName', ['Stmt']) -- template-haskell-2.17++-- _MDoE :: 'Prism'' 'Exp' ['Stmt']                  -- Earlier versions+-- @+# if MIN_VERSION_template_haskell(2,17,0)+_MDoE :: Prism' Exp (Maybe ModName, [Stmt])+_MDoE+  = prism' reviewer remitter+  where+      reviewer (x, y) = MDoE x y+      remitter (MDoE x y) = Just (x, y)+      remitter _ = Nothing+# else+_MDoE :: Prism' Exp [Stmt]+_MDoE+  = prism' reviewer remitter+  where+      reviewer = MDoE+      remitter (MDoE x) = Just x+      remitter _ = Nothing+# endif++_ImplicitParamVarE :: Prism' Exp String+_ImplicitParamVarE+  = prism' reviewer remitter+  where+      reviewer = ImplicitParamVarE+      remitter (ImplicitParamVarE x) = Just x+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,18,0)+_GetFieldE :: Prism' Exp (Exp, String)+_GetFieldE+  = prism' reviewer remitter+  where+      reviewer (x, y) = GetFieldE x y+      remitter (GetFieldE x y) = Just (x, y)+      remitter _ = Nothing++_ProjectionE :: Prism' Exp (NonEmpty String)+_ProjectionE+  = prism' reviewer remitter+  where+      reviewer = ProjectionE+      remitter (ProjectionE x) = Just x+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,19,0)+_LamCasesE :: Prism' Exp [Clause]+_LamCasesE+  = prism' reviewer remitter+  where+      reviewer = LamCasesE+      remitter (LamCasesE x) = Just x+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,21,0)+_TypedBracketE :: Prism' Exp Exp+_TypedBracketE+  = prism' reviewer remitter+  where+      reviewer = TypedBracketE+      remitter (TypedBracketE x) = Just x+      remitter _ = Nothing++_TypedSpliceE :: Prism' Exp Exp+_TypedSpliceE+  = prism' reviewer remitter+  where+      reviewer = TypedSpliceE+      remitter (TypedSpliceE x) = Just x+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,22,0)+_TypeE :: Prism' Exp Type+_TypeE+  = prism' reviewer remitter+  where+      reviewer = TypeE+      remitter (TypeE x) = Just x+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,23,0)+_ForallE :: Prism' Exp ([TyVarBndr Specificity], Exp)+_ForallE+  = prism' reviewer remitter+  where+      reviewer (x, y) = ForallE x y+      remitter (ForallE x y) = Just (x, y)+      remitter _ = Nothing++_ForallVisE :: Prism' Exp ([TyVarBndr ()], Exp)+_ForallVisE+  = prism' reviewer remitter+  where+      reviewer (x, y) = ForallVisE x y+      remitter (ForallVisE x y) = Just (x, y)+      remitter _ = Nothing++_ConstrainedE :: Prism' Exp ([Exp], Exp)+_ConstrainedE+  = prism' reviewer remitter+  where+      reviewer (x, y) = ConstrainedE x y+      remitter (ConstrainedE x y) = Just (x, y)+      remitter _ = Nothing+#endif++_GuardedB :: Prism' Body [(Guard, Exp)]+_GuardedB+  = prism' reviewer remitter+  where+      reviewer = GuardedB+      remitter (GuardedB x) = Just x+      remitter _ = Nothing++_NormalB :: Prism' Body Exp+_NormalB+  = prism' reviewer remitter+  where+      reviewer = NormalB+      remitter (NormalB x) = Just x+      remitter _ = Nothing++_NormalG :: Prism' Guard Exp+_NormalG+  = prism' reviewer remitter+  where+      reviewer = NormalG+      remitter (NormalG x) = Just x+      remitter _ = Nothing++_PatG :: Prism' Guard [Stmt]+_PatG+  = prism' reviewer remitter+  where+      reviewer = PatG+      remitter (PatG x) = Just x+      remitter _ = Nothing++_BindS :: Prism' Stmt (Pat, Exp)+_BindS+  = prism' reviewer remitter+  where+      reviewer (x, y) = BindS x y+      remitter (BindS x y) = Just (x, y)+      remitter _ = Nothing++_LetS :: Prism' Stmt [Dec]+_LetS+  = prism' reviewer remitter+  where+      reviewer = LetS+      remitter (LetS x) = Just x+      remitter _ = Nothing++_NoBindS :: Prism' Stmt Exp+_NoBindS+  = prism' reviewer remitter+  where+      reviewer = NoBindS+      remitter (NoBindS x) = Just x+      remitter _ = Nothing++_ParS :: Prism' Stmt [[Stmt]]+_ParS+  = prism' reviewer remitter+  where+      reviewer = ParS+      remitter (ParS x) = Just x+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,15,0)+_RecS :: Prism' Stmt [Stmt]+_RecS+  = prism' reviewer remitter+  where+      reviewer = RecS+      remitter (RecS x) = Just x+      remitter _ = Nothing+#endif++_FromR :: Prism' Range Exp+_FromR+  = prism' reviewer remitter+  where+      reviewer = FromR+      remitter (FromR x) = Just x+      remitter _ = Nothing++_FromThenR :: Prism' Range (Exp, Exp)+_FromThenR+  = prism' reviewer remitter+  where+      reviewer (x, y) = FromThenR x y+      remitter (FromThenR x y) = Just (x, y)+      remitter _ = Nothing++_FromToR :: Prism' Range (Exp, Exp)+_FromToR+  = prism' reviewer remitter+  where+      reviewer (x, y) = FromToR x y+      remitter (FromToR x y) = Just (x, y)+      remitter _ = Nothing++_FromThenToR :: Prism' Range (Exp, Exp, Exp)+_FromThenToR+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = FromThenToR x y z+      remitter (FromThenToR x y z) = Just (x, y, z)+      remitter _ = Nothing++_CharL :: Prism' Lit Char+_CharL+  = prism' reviewer remitter+  where+      reviewer = CharL+      remitter (CharL x) = Just x+      remitter _ = Nothing++_StringL :: Prism' Lit String+_StringL+  = prism' reviewer remitter+  where+      reviewer = StringL+      remitter (StringL x) = Just x+      remitter _ = Nothing++_IntegerL :: Prism' Lit Integer+_IntegerL+  = prism' reviewer remitter+  where+      reviewer = IntegerL+      remitter (IntegerL x) = Just x+      remitter _ = Nothing++_RationalL :: Prism' Lit Rational+_RationalL+  = prism' reviewer remitter+  where+      reviewer = RationalL+      remitter (RationalL x) = Just x+      remitter _ = Nothing++_IntPrimL :: Prism' Lit Integer+_IntPrimL+  = prism' reviewer remitter+  where+      reviewer = IntPrimL+      remitter (IntPrimL x) = Just x+      remitter _ = Nothing++_WordPrimL :: Prism' Lit Integer+_WordPrimL+  = prism' reviewer remitter+  where+      reviewer = WordPrimL+      remitter (WordPrimL x) = Just x+      remitter _ = Nothing++_FloatPrimL :: Prism' Lit Rational+_FloatPrimL+  = prism' reviewer remitter+  where+      reviewer = FloatPrimL+      remitter (FloatPrimL x) = Just x+      remitter _ = Nothing++_DoublePrimL :: Prism' Lit Rational+_DoublePrimL+  = prism' reviewer remitter+  where+      reviewer = DoublePrimL+      remitter (DoublePrimL x) = Just x+      remitter _ = Nothing++_StringPrimL :: Prism' Lit [Word8]+_StringPrimL+  = prism' reviewer remitter+  where+      reviewer = StringPrimL+      remitter (StringPrimL x) = Just x+      remitter _ = Nothing++_CharPrimL :: Prism' Lit Char+_CharPrimL+  = prism' reviewer remitter+  where+      reviewer = CharPrimL+      remitter (CharPrimL x) = Just x+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,16,0)+_BytesPrimL :: Prism' Lit Bytes+_BytesPrimL+  = prism' reviewer remitter+  where+      reviewer = BytesPrimL+      remitter (BytesPrimL x) = Just x+      remitter _ = Nothing+#endif++_LitP :: Prism' Pat Lit+_LitP+  = prism' reviewer remitter+  where+      reviewer = LitP+      remitter (LitP x) = Just x+      remitter _ = Nothing++_VarP :: Prism' Pat Name+_VarP+  = prism' reviewer remitter+  where+      reviewer = VarP+      remitter (VarP x) = Just x+      remitter _ = Nothing++_TupP :: Prism' Pat [Pat]+_TupP+  = prism' reviewer remitter+  where+      reviewer = TupP+      remitter (TupP x) = Just x+      remitter _ = Nothing++_UnboxedTupP :: Prism' Pat [Pat]+_UnboxedTupP+  = prism' reviewer remitter+  where+      reviewer = UnboxedTupP+      remitter (UnboxedTupP x) = Just x+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,12,0)+_UnboxedSumP :: Prism' Pat (Pat, SumAlt, SumArity)+_UnboxedSumP+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = UnboxedSumP x y z+      remitter (UnboxedSumP x y z) = Just (x, y, z)+      remitter _ = Nothing+#endif++-- |+-- @+-- _ConP :: 'Prism'' 'Pat' ('Name', ['Type'], ['Pat']) -- template-haskell-2.18++-- _ConP :: 'Prism'' 'Pat' ('Name',         ['Pat']) -- Earlier versions+-- @+#if MIN_VERSION_template_haskell(2,18,0)+_ConP :: Prism' Pat (Name, [Type], [Pat])+_ConP+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = ConP x y z+      remitter (ConP x y z) = Just (x, y, z)+      remitter _ = Nothing+#else+_ConP :: Prism' Pat (Name, [Pat])+_ConP+  = prism' reviewer remitter+  where+      reviewer (x, y) = ConP x y+      remitter (ConP x y) = Just (x, y)+      remitter _ = Nothing+#endif++_InfixP :: Prism' Pat (Pat, Name, Pat)+_InfixP+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = InfixP x y z+      remitter (InfixP x y z) = Just (x, y, z)+      remitter _ = Nothing++_UInfixP :: Prism' Pat (Pat, Name, Pat)+_UInfixP+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = UInfixP x y z+      remitter (UInfixP x y z) = Just (x, y, z)+      remitter _ = Nothing++_ParensP :: Prism' Pat Pat+_ParensP+  = prism' reviewer remitter+  where+      reviewer = ParensP+      remitter (ParensP x) = Just x+      remitter _ = Nothing++_TildeP :: Prism' Pat Pat+_TildeP+  = prism' reviewer remitter+  where+      reviewer = TildeP+      remitter (TildeP x) = Just x+      remitter _ = Nothing++_BangP :: Prism' Pat Pat+_BangP+  = prism' reviewer remitter+  where+      reviewer = BangP+      remitter (BangP x) = Just x+      remitter _ = Nothing++_AsP :: Prism' Pat (Name, Pat)+_AsP+  = prism' reviewer remitter+  where+      reviewer (x, y) = AsP x y+      remitter (AsP x y) = Just (x, y)+      remitter _ = Nothing++_WildP :: Prism' Pat ()+_WildP+  = prism' reviewer remitter+  where+      reviewer () = WildP+      remitter WildP = Just ()+      remitter _ = Nothing++_RecP :: Prism' Pat (Name, [FieldPat])+_RecP+  = prism' reviewer remitter+  where+      reviewer (x, y) = RecP x y+      remitter (RecP x y) = Just (x, y)+      remitter _ = Nothing++_ListP :: Prism' Pat [Pat]+_ListP+  = prism' reviewer remitter+  where+      reviewer = ListP+      remitter (ListP x) = Just x+      remitter _ = Nothing++_SigP :: Prism' Pat (Pat, Type)+_SigP+  = prism' reviewer remitter+  where+      reviewer (x, y) = SigP x y+      remitter (SigP x y) = Just (x, y)+      remitter _ = Nothing++_ViewP :: Prism' Pat (Exp, Pat)+_ViewP+  = prism' reviewer remitter+  where+      reviewer (x, y) = ViewP x y+      remitter (ViewP x y) = Just (x, y)+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,22,0)+_TypeP :: Prism' Pat Type+_TypeP+  = prism' reviewer remitter+  where+      reviewer = TypeP+      remitter (TypeP x) = Just x+      remitter _ = Nothing++_InvisP :: Prism' Pat Type+_InvisP+  = prism' reviewer remitter+  where+      reviewer = InvisP+      remitter (InvisP x) = Just x+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,23,0)+_OrP :: Prism' Pat (NonEmpty Pat)+_OrP+  = prism' reviewer remitter+  where+      reviewer = OrP+      remitter (OrP x) = Just x+      remitter _ = Nothing+#endif++_ForallT :: Prism' Type ([TyVarBndrSpec], Cxt, Type)+_ForallT+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = ForallT x y z+      remitter (ForallT x y z) = Just (x, y, z)+      remitter _ = Nothing++_AppT :: Prism' Type (Type, Type)+_AppT+  = prism' reviewer remitter+  where+      reviewer (x, y) = AppT x y+      remitter (AppT x y) = Just (x, y)+      remitter _ = Nothing++_SigT :: Prism' Type (Type, Kind)+_SigT+  = prism' reviewer remitter+  where+      reviewer (x, y) = SigT x y+      remitter (SigT x y) = Just (x, y)+      remitter _ = Nothing++_VarT :: Prism' Type Name+_VarT+  = prism' reviewer remitter+  where+      reviewer = VarT+      remitter (VarT x) = Just x+      remitter _ = Nothing++_ConT :: Prism' Type Name+_ConT+  = prism' reviewer remitter+  where+      reviewer = ConT+      remitter (ConT x) = Just x+      remitter _ = Nothing++_PromotedT :: Prism' Type Name+_PromotedT+  = prism' reviewer remitter+  where+      reviewer = PromotedT+      remitter (PromotedT x) = Just x+      remitter _ = Nothing++_TupleT :: Prism' Type Int+_TupleT+  = prism' reviewer remitter+  where+      reviewer = TupleT+      remitter (TupleT x) = Just x+      remitter _ = Nothing++_UnboxedTupleT :: Prism' Type Int+_UnboxedTupleT+  = prism' reviewer remitter+  where+      reviewer = UnboxedTupleT+      remitter (UnboxedTupleT x) = Just x+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,12,0)+_UnboxedSumT :: Prism' Type SumArity+_UnboxedSumT+  = prism' reviewer remitter+  where+      reviewer = UnboxedSumT+      remitter (UnboxedSumT x) = Just x+      remitter _ = Nothing+#endif++_ArrowT :: Prism' Type ()+_ArrowT+  = prism' reviewer remitter+  where+      reviewer () = ArrowT+      remitter ArrowT = Just ()+      remitter _ = Nothing++_EqualityT :: Prism' Type ()+_EqualityT+  = prism' reviewer remitter+  where+      reviewer () = EqualityT+      remitter EqualityT = Just ()+      remitter _ = Nothing++_ListT :: Prism' Type ()+_ListT+  = prism' reviewer remitter+  where+      reviewer () = ListT+      remitter ListT = Just ()+      remitter _ = Nothing++_PromotedTupleT :: Prism' Type Int+_PromotedTupleT+  = prism' reviewer remitter+  where+      reviewer = PromotedTupleT+      remitter (PromotedTupleT x) = Just x+      remitter _ = Nothing++_PromotedNilT :: Prism' Type ()+_PromotedNilT+  = prism' reviewer remitter+  where+      reviewer () = PromotedNilT+      remitter PromotedNilT = Just ()+      remitter _ = Nothing++_PromotedConsT :: Prism' Type ()+_PromotedConsT+  = prism' reviewer remitter+  where+      reviewer () = PromotedConsT+      remitter PromotedConsT = Just ()+      remitter _ = Nothing++_StarT :: Prism' Type ()+_StarT+  = prism' reviewer remitter+  where+      reviewer () = StarT+      remitter StarT = Just ()+      remitter _ = Nothing++_ConstraintT :: Prism' Type ()+_ConstraintT+  = prism' reviewer remitter+  where+      reviewer () = ConstraintT+      remitter ConstraintT = Just ()+      remitter _ = Nothing++_LitT :: Prism' Type TyLit+_LitT+  = prism' reviewer remitter+  where+      reviewer = LitT+      remitter (LitT x) = Just x+      remitter _ = Nothing++_InfixT :: Prism' Type (Type, Name, Type)+_InfixT+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = InfixT x y z+      remitter (InfixT x y z) = Just (x, y, z)+      remitter _ = Nothing++_UInfixT :: Prism' Type (Type, Name, Type)+_UInfixT+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = UInfixT x y z+      remitter (UInfixT x y z) = Just (x, y, z)+      remitter _ = Nothing++_ParensT :: Prism' Type Type+_ParensT+  = prism' reviewer remitter+  where+      reviewer = ParensT+      remitter (ParensT x) = Just x+      remitter _ = Nothing++_WildCardT :: Prism' Type ()+_WildCardT+  = prism' reviewer remitter+  where+      reviewer () = WildCardT+      remitter WildCardT = Just ()+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,15,0)+_AppKindT :: Prism' Type (Type, Kind)+_AppKindT+  = prism' reviewer remitter+  where+      reviewer (x, y) = AppKindT x y+      remitter (AppKindT x y) = Just (x, y)+      remitter _ = Nothing++_ImplicitParamT :: Prism' Type (String, Type)+_ImplicitParamT+  = prism' reviewer remitter+  where+      reviewer (x, y) = ImplicitParamT x y+      remitter (ImplicitParamT x y) = Just (x, y)+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,16,0)+_ForallVisT :: Prism' Type ([TyVarBndrUnit], Type)+_ForallVisT+  = prism' reviewer remitter+  where+      reviewer (x, y) = ForallVisT x y+      remitter (ForallVisT x y) = Just (x, y)+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,17,0)+_MulArrowT :: Prism' Type ()+_MulArrowT+  = prism' reviewer remitter+  where+      reviewer () = MulArrowT+      remitter MulArrowT = Just ()+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,19,0)+_PromotedInfixT :: Prism' Type (Type, Name, Type)+_PromotedInfixT+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = PromotedInfixT x y z+      remitter (PromotedInfixT x y z) = Just (x, y, z)+      remitter _ = Nothing++_PromotedUInfixT :: Prism' Type (Type, Name, Type)+_PromotedUInfixT+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = PromotedUInfixT x y z+      remitter (PromotedUInfixT x y z) = Just (x, y, z)+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,17,0)+_SpecifiedSpec :: Prism' Specificity ()+_SpecifiedSpec+  = prism' reviewer remitter+  where+      reviewer () = SpecifiedSpec+      remitter SpecifiedSpec = Just ()+      remitter _ = Nothing++_InferredSpec :: Prism' Specificity ()+_InferredSpec+  = prism' reviewer remitter+  where+      reviewer () = InferredSpec+      remitter InferredSpec = Just ()+      remitter _ = Nothing+#endif++#if MIN_VERSION_template_haskell(2,21,0)+_BndrReq :: Prism' BndrVis ()+_BndrReq+  = prism' reviewer remitter+  where+      reviewer () = BndrReq+      remitter BndrReq = Just ()+      remitter _ = Nothing++_BndrInvis :: Prism' BndrVis ()+_BndrInvis+  = prism' reviewer remitter+  where+      reviewer () = BndrInvis+      remitter BndrInvis = Just ()+      remitter _ = Nothing+#endif++-- |+-- @+-- _PlainTV :: 'Prism'' ('TyVarBndr' flag) ('Name', flag) -- template-haskell-2.17++-- _PlainTV :: 'Prism''  'TyVarBndr'        'Name'        -- Earlier versions+-- @+#if MIN_VERSION_template_haskell(2,17,0)+_PlainTV :: Prism' (TyVarBndr flag) (Name, flag)+_PlainTV+  = prism' reviewer remitter+  where+      reviewer (x, y) = PlainTV x y+      remitter (PlainTV x y) = Just (x, y)+      remitter _ = Nothing+#else+_PlainTV :: Prism' TyVarBndr Name+_PlainTV+  = prism' reviewer remitter+  where+      reviewer = PlainTV+      remitter (PlainTV x) = Just x+      remitter _ = Nothing+#endif++-- |+-- @+-- _KindedTV :: 'Prism'' ('TyVarBndr' flag) ('Name', flag, 'Kind') -- template-haskell-2.17++-- _KindedTV :: 'Prism''  'TyVarBndr'       ('Name',       'Kind') -- Earlier versions+-- @+#if MIN_VERSION_template_haskell(2,17,0)+_KindedTV :: Prism' (TyVarBndr flag) (Name, flag, Kind)+_KindedTV+  = prism' reviewer remitter+  where+      reviewer (x, y, z) = KindedTV x y z+      remitter (KindedTV x y z) = Just (x, y, z)+      remitter _ = Nothing+#else+_KindedTV :: Prism' TyVarBndr (Name, Kind)+_KindedTV+  = prism' reviewer remitter+  where+      reviewer (x, y) = KindedTV x y+      remitter (KindedTV x y) = Just (x, y)+      remitter _ = Nothing+#endif++_NoSig :: Prism' FamilyResultSig ()+_NoSig+  = prism' reviewer remitter+  where+      reviewer () = NoSig+      remitter NoSig = Just ()+      remitter _ = Nothing++_KindSig :: Prism' FamilyResultSig Kind+_KindSig+  = prism' reviewer remitter+  where+      reviewer = KindSig+      remitter (KindSig x) = Just x+      remitter _ = Nothing++_TyVarSig :: Prism' FamilyResultSig TyVarBndrUnit+_TyVarSig+  = prism' reviewer remitter+  where+      reviewer = TyVarSig+      remitter (TyVarSig x) = Just x+      remitter _ = Nothing++_NumTyLit :: Prism' TyLit Integer+_NumTyLit+  = prism' reviewer remitter+  where+      reviewer = NumTyLit+      remitter (NumTyLit x) = Just x+      remitter _ = Nothing++_StrTyLit :: Prism' TyLit String+_StrTyLit+  = prism' reviewer remitter+  where+      reviewer = StrTyLit+      remitter (StrTyLit x) = Just x+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,18,0)+_CharTyLit :: Prism' TyLit Char+_CharTyLit+  = prism' reviewer remitter+  where+      reviewer = CharTyLit+      remitter (CharTyLit x) = Just x+      remitter _ = Nothing+#endif++_NominalR :: Prism' Role ()+_NominalR+  = prism' reviewer remitter+  where+      reviewer () = NominalR+      remitter NominalR = Just ()+      remitter _ = Nothing++_RepresentationalR :: Prism' Role ()+_RepresentationalR+  = prism' reviewer remitter+  where+      reviewer () = RepresentationalR+      remitter RepresentationalR = Just ()+      remitter _ = Nothing++_PhantomR :: Prism' Role ()+_PhantomR+  = prism' reviewer remitter+  where+      reviewer () = PhantomR+      remitter PhantomR = Just ()+      remitter _ = Nothing++_InferR :: Prism' Role ()+_InferR+  = prism' reviewer remitter+  where+      reviewer () = InferR+      remitter InferR = Just ()+      remitter _ = Nothing++#if MIN_VERSION_template_haskell(2,12,0)+_StockStrategy :: Prism' DerivStrategy ()+_StockStrategy+  = prism' reviewer remitter+  where+      reviewer () = StockStrategy+      remitter StockStrategy = Just ()+      remitter _ = Nothing++_AnyclassStrategy :: Prism' DerivStrategy ()+_AnyclassStrategy+  = prism' reviewer remitter+  where+      reviewer () = AnyclassStrategy+      remitter AnyclassStrategy = Just ()+      remitter _ = Nothing++_NewtypeStrategy :: Prism' DerivStrategy ()+_NewtypeStrategy+  = prism' reviewer remitter+  where+      reviewer () = NewtypeStrategy+      remitter NewtypeStrategy = Just ()+      remitter _ = Nothing+#endif
+ src/Numeric/Lens.hs view
@@ -0,0 +1,192 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-}+--------------------------------------------------------------------------------+-- |+-- Module      :  Numeric.Lens+-- Copyright   :  (C) 2012-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  portable+-------------------------------------------------------------------------------+module Numeric.Lens+  ( base+  , integral+    -- * Predefined bases+  , binary+  , octal+  , decimal+  , hex+    -- * Arithmetic lenses+  , adding+  , subtracting+  , multiplying+  , dividing+  , exponentiating+  , negated+  , pattern Integral+  ) where++import Control.Lens+import Data.CallStack+import Data.Char (chr, ord, isAsciiLower, isAsciiUpper, isDigit)+import Data.Maybe (fromMaybe)+import Numeric (readInt, showIntAtBase)++-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import Data.Monoid (Sum(..))++-- | This t'Prism' can be used to model the fact that every t'Integral'+-- type is a subset of 'Integer'.+--+-- Embedding through the t'Prism' only succeeds if the 'Integer' would pass+-- through unmodified when re-extracted.+integral :: (Integral a, Integral b) => Prism Integer Integer a b+integral = prism toInteger $ \ i -> let a = fromInteger i in+  if toInteger a == i+  then Right a+  else Left i++pattern Integral :: Integral a => a -> Integer+pattern Integral a <- (preview integral -> Just a) where+  Integral a = review integral a++-- | A prism that shows and reads integers in base-2 through base-36+--+-- Note: This is an improper prism, since leading 0s are stripped when reading.+--+-- >>> "100" ^? base 16+-- Just 256+--+-- >>> 1767707668033969 ^. re (base 36)+-- "helloworld"+base :: (HasCallStack, Integral a) => Int -> Prism' String a+base b+  | b < 2 || b > 36 = error ("base: Invalid base " ++ show b)+  | otherwise       = prism intShow intRead+  where+    intShow n = showSigned' (showIntAtBase (toInteger b) intToDigit') (toInteger n) ""++    intRead s =+      case readSigned' (readInt (fromIntegral b) (isDigit' b) digitToInt') s of+        [(n,"")] -> Right n+        _ -> Left s+{-# INLINE base #-}++-- | Like 'Data.Char.intToDigit', but handles up to base-36+intToDigit' :: HasCallStack => Int -> Char+intToDigit' i+  | i >= 0  && i < 10 = chr (ord '0' + i)+  | i >= 10 && i < 36 = chr (ord 'a' + i - 10)+  | otherwise = error ("intToDigit': Invalid int " ++ show i)++-- | Like 'Data.Char.digitToInt', but handles up to base-36+digitToInt' :: HasCallStack => Char -> Int+digitToInt' c = fromMaybe (error ("digitToInt': Invalid digit " ++ show c))+                          (digitToIntMay c)++-- | A safe variant of 'digitToInt''+digitToIntMay :: Char -> Maybe Int+digitToIntMay c+  | isDigit c      = Just (ord c - ord '0')+  | isAsciiLower c = Just (ord c - ord 'a' + 10)+  | isAsciiUpper c = Just (ord c - ord 'A' + 10)+  | otherwise = Nothing++-- | Select digits that fall into the given base+isDigit' :: Int -> Char -> Bool+isDigit' b c = case digitToIntMay c of+  Just i -> i < b+  _ -> False++-- | A simpler variant of 'Numeric.showSigned' that only prepends a dash and+-- doesn't know about parentheses+showSigned' :: Real a => (a -> ShowS) -> a -> ShowS+showSigned' f n+  | n < 0     = showChar '-' . f (negate n)+  | otherwise = f n++-- | A simpler variant of 'Numeric.readSigned' that supports any base, only+-- recognizes an initial dash and doesn't know about parentheses+readSigned' :: Real a => ReadS a -> ReadS a+readSigned' f ('-':xs) = f xs <&> _1 %~ negate+readSigned' f xs       = f xs++-- | @'binary' = 'base' 2@+binary :: Integral a => Prism' String a+binary = base 2++-- | @'octal' = 'base' 8@+octal :: Integral a => Prism' String a+octal = base 8++-- | @'decimal' = 'base' 10@+decimal :: Integral a => Prism' String a+decimal = base 10++-- | @'hex' = 'base' 16@+hex :: Integral a => Prism' String a+hex = base 16++-- | @'adding' n = 'iso' (+n) (subtract n)@+--+-- >>> [1..3]^..traverse.adding 1000+-- [1001,1002,1003]+adding :: Num a => a -> Iso' a a+adding n = iso (+n) (subtract n)++-- | @+-- 'subtracting' n = 'iso' (subtract n) ((+n)+-- 'subtracting' n = 'from' ('adding' n)+-- @+subtracting :: Num a => a -> Iso' a a+subtracting n = iso (subtract n) (+n)++-- | @'multiplying' n = iso (*n) (/n)@+--+-- Note: This errors for n = 0+--+-- >>> 5 & multiplying 1000 +~ 3+-- 5.003+--+-- >>> let fahrenheit = multiplying (9/5).adding 32 in 230^.from fahrenheit+-- 110.0+multiplying :: (Fractional a, Eq a) => a -> Iso' a a+multiplying 0 = error "Numeric.Lens.multiplying: factor 0"+multiplying n = iso (*n) (/n)++-- | @+-- 'dividing' n = 'iso' (/n) (*n)+-- 'dividing' n = 'from' ('multiplying' n)@+--+-- Note: This errors for n = 0+dividing :: (Fractional a, Eq a) => a -> Iso' a a+dividing 0 = error "Numeric.Lens.dividing: divisor 0"+dividing n = iso (/n) (*n)++-- | @'exponentiating' n = 'iso' (**n) (**recip n)@+--+-- Note: This errors for n = 0+--+-- >>> au (_Wrapping Sum . from (exponentiating 2)) (foldMapOf each) (3,4) == 5+-- True+exponentiating :: (Floating a, Eq a) => a -> Iso' a a+exponentiating 0 = error "Numeric.Lens.exponentiating: exponent 0"+exponentiating n = iso (**n) (**recip n)+++-- | @'negated' = 'iso' 'negate' 'negate'@+--+-- >>> au (_Wrapping Sum . negated) (foldMapOf each) (3,4) == 7+-- True+--+-- >>> au (_Wrapping Sum) (foldMapOf (each.negated)) (3,4) == -7+-- True+negated :: Num a => Iso' a a+negated = iso negate negate
+ src/Numeric/Natural/Lens.hs view
@@ -0,0 +1,85 @@+{-# language RankNTypes #-}+{-# language PatternGuards #-}+{-# language ViewPatterns #-}+{-# language PatternSynonyms #-}+--------------------------------------------------------------------------------+-- |+-- Module      :  Numeric.Natural.Lens+-- Copyright   :  (C) 2017 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  portable+--+-- Useful tools for Gödel numbering.+-------------------------------------------------------------------------------+module Numeric.Natural.Lens+  ( _Pair+  , _Sum+  , _Naturals+  , pattern Pair+  , pattern Sum+  , pattern Naturals+  ) where++import Control.Lens+import Numeric.Natural++-- | The natural numbers are isomorphic to the product of the natural numbers with itself.+--+-- @N = N*N@+_Pair :: Iso' Natural (Natural, Natural)+_Pair = iso hither (uncurry yon) where+  yon 0 0 = 0+  yon m n = case quotRem m 2 of+    (q,r) -> r + 2 * yon n q -- rotation++  hither 0 = (0,0)+  hither n = case quotRem n 2 of+   (p,r) -> case hither p of+     (x,y) -> (r+2*y,x) -- rotation++-- | The natural numbers are isomorphic to disjoint sums of natural numbers embedded as+-- evens or odds.+--+-- @N = 2*N@+_Sum :: Iso' Natural (Either Natural Natural)+_Sum = iso hither yon where+  hither p = case quotRem p 2 of+    (q,0) -> Left q+    (q,1) -> Right q+    _     -> error "_Sum: impossible"+  yon (Left q)  = 2*q+  yon (Right q) = 2*q+1++-- | The natural numbers are isomorphic to lists of natural numbers+_Naturals :: Iso' Natural [Natural]+_Naturals = iso hither yon where+  hither 0 = []+  hither n | (h, t) <- (n-1)^._Pair = h : hither t+  yon [] = 0+  yon (x:xs) = 1 + review _Pair (x, yon xs)++-- |+-- interleaves the bits of two natural numbers+pattern Pair :: Natural -> Natural -> Natural+pattern Pair x y <- (view _Pair -> (x,y)) where+  Pair x y = review _Pair (x,y)++-- |+-- @+-- Sum (Left q) = 2*q+-- Sum (Right q) = 2*q+1+-- @+pattern Sum :: Either Natural Natural -> Natural+pattern Sum s <- (view _Sum -> s) where+  Sum s = review _Sum s++-- |+-- @+-- Naturals [] = 0+-- Naturals (h:t) = 1 + Pair h (Naturals t)+-- @+pattern Naturals :: [Natural] -> Natural+pattern Naturals xs <- (view _Naturals -> xs) where+  Naturals xs = review _Naturals xs
+ src/System/Exit/Lens.hs view
@@ -0,0 +1,77 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  System.Exit.Lens+-- Copyright   :  (C) 2013-16 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  Control.Exception+--+-- These prisms can be used with the combinators in "Control.Exception.Lens".+----------------------------------------------------------------------------+module System.Exit.Lens+  ( AsExitCode(..)+  , _ExitFailure+  , _ExitSuccess+  , pattern ExitFailure_+  , pattern ExitSuccess_+  ) where++import Prelude ()++import Control.Exception+import Control.Exception.Lens+import Control.Lens+import Control.Lens.Internal.Prelude+import System.Exit++-- | Exit codes that a program can return with:+class AsExitCode t where+  _ExitCode :: Prism' t ExitCode++instance AsExitCode ExitCode where+  _ExitCode = id+  {-# INLINE _ExitCode #-}++instance AsExitCode SomeException where+  _ExitCode = exception+  {-# INLINE _ExitCode #-}++-- | indicates successful termination;+--+-- @+-- '_ExitSuccess' :: 'Prism'' 'ExitCode'      ()+-- '_ExitSuccess' :: 'Prism'' 'SomeException' ()+-- @+_ExitSuccess :: AsExitCode t => Prism' t ()+_ExitSuccess = _ExitCode . dimap seta (either id id) . right' . rmap (ExitSuccess <$) where+  seta ExitSuccess = Right ()+  seta t           = Left  (pure t)+{-# INLINE _ExitSuccess #-}+++-- | indicates program failure with an exit code. The exact interpretation of the code is operating-system dependent. In particular, some values may be prohibited (e.g. 0 on a POSIX-compliant system).+--+-- @+-- '_ExitFailure' :: 'Prism'' 'ExitCode'      'Int'+-- '_ExitFailure' :: 'Prism'' 'SomeException' 'Int'+-- @+_ExitFailure :: AsExitCode t => Prism' t Int+_ExitFailure = _ExitCode . dimap seta (either id id) . right' . rmap (fmap ExitFailure) where+  seta (ExitFailure i) = Right i+  seta t               = Left  (pure t)+{-# INLINE _ExitFailure #-}++pattern ExitSuccess_ :: AsExitCode s => s+pattern ExitSuccess_ <- (has _ExitSuccess -> True) where+  ExitSuccess_ = review _ExitSuccess ()++pattern ExitFailure_ :: AsExitCode s => Int -> s+pattern ExitFailure_ a <- (preview _ExitFailure -> Just a) where+  ExitFailure_ a = review _ExitFailure a
src/System/FilePath/Lens.hs view
@@ -1,7 +1,7 @@ ----------------------------------------------------------------------------- -- | -- Module      :  System.FilePath.Lens--- Copyright   :  (C) 2012 Edward Kmett+-- Copyright   :  (C) 2012-16 Edward Kmett -- License     :  BSD-style (see the file LICENSE) -- Maintainer  :  Edward Kmett <ekmett@gmail.com> -- Stability   :  experimental@@ -9,152 +9,239 @@ -- ---------------------------------------------------------------------------- module System.FilePath.Lens-  ( (</>~), (<</>~), (<.>~), (<<.>~)-  , (</>=), (<</>=), (<.>=), (<<.>=)+  (+  -- * Operators+    (</>~), (<</>~), (<<</>~), (<.>~), (<<.>~), (<<<.>~)+  , (</>=), (<</>=), (<<</>=), (<.>=), (<<.>=), (<<<.>=)+  -- * Lenses   , basename, directory, extension, filename   ) where -import Control.Applicative ((<$>))+import Prelude () -import Control.Monad.State.Class as State+import Control.Monad.State as State import System.FilePath   ( (</>), (<.>), splitExtension   , takeBaseName, takeDirectory   , takeExtension, takeFileName   ) +import Control.Lens.Internal.Prelude import Control.Lens hiding ((<.>)) -infixr 4 </>~, <</>~, <.>~, <<.>~-infix 4 </>=, <</>=, <.>=, <<.>=+-- $setup+-- >>> :set -XNoOverloadedStrings+-- >>> import Control.Lens+-- >>> import Control.Monad.State+-- >>> import System.FilePath ((</>)) +{- NB: Be very careful if you are planning to modify the doctest output in+this module! Path separators are OS-dependent (\\ with Windows, / with Posix),+so we take great care to avoid using separators in doctest output so that they+will be valid on all operating systems.++If you find yourself wanting to test a function that uses path separators in+the output, it would be wise to:++1. Compare the tested expression and the expected results explicitly using (==).+2. Always use the </> function (and derived combinators) to construct path+   separators instead of typing them manually. That is, don't type out+   "foo/bar", but rather "foo" </> "bar".++This way we can avoid leaking path separators into the output. See the doctest+example for (</>~) for an example of how to do this.+-}++infixr 4 </>~, <</>~, <<</>~, <.>~, <<.>~, <<<.>~+infix 4 </>=, <</>=, <<</>=, <.>=, <<.>=, <<<.>=+ -- | Modify the path by adding another path. ----- >>> :m + Control.Lens--- >>> both </>~ "!!!" $ ("hello","world")--- ("hello/!!!","world/!!!")+-- >>> (both </>~ "bin" $ ("hello","world")) == ("hello" </> "bin", "world" </> "bin")+-- True -- -- @--- ('</>~') :: 'Setter' a b 'FilePath' 'FilePath' -> 'FilePath' -> a -> b--- ('</>~') :: 'Iso' a b 'FilePath' 'FilePath' -> 'FilePath' -> a -> b--- ('</>~') :: 'Lens' a b 'FilePath' 'FilePath' -> 'FilePath' -> a -> b--- ('</>~') :: 'Traversal' a b 'FilePath' 'FilePath' -> 'FilePath' -> a -> b+-- ('</>~') :: t'Setter' s a 'FilePath' 'FilePath' -> 'FilePath' -> s -> a+-- ('</>~') :: t'Iso' s a 'FilePath' 'FilePath' -> 'FilePath' -> s -> a+-- ('</>~') :: t'Lens' s a 'FilePath' 'FilePath' -> 'FilePath' -> s -> a+-- ('</>~') :: t'Traversal' s a 'FilePath' 'FilePath' -> 'FilePath' -> s -> a -- @-(</>~) :: Setting a b FilePath FilePath -> FilePath -> a -> b+(</>~) :: ASetter s t FilePath FilePath -> FilePath -> s -> t l </>~ n = over l (</> n) {-# INLINE (</>~) #-}  --- | Modify the target(s) of a 'Simple' 'Lens', 'Iso', 'Setter' or 'Traversal' by adding a path.+-- | Modify the target(s) of a 'Lens'', 'Iso'', 'Setter'' or 'Traversal'' by adding a path. --+-- >>> execState (both </>= "bin") ("hello","world") == ("hello" </> "bin", "world" </> "bin")+-- True+-- -- @--- ('</>=') :: 'MonadState' a m => 'Simple' 'Setter' a 'FilePath' -> 'FilePath' -> m ()--- ('</>=') :: 'MonadState' a m => 'Simple' 'Iso' a 'FilePath' -> 'FilePath' -> m ()--- ('</>=') :: 'MonadState' a m => 'Simple' 'Lens' a 'FilePath' -> 'FilePath' -> m ()--- ('</>=') :: 'MonadState' a m => 'Simple' 'Traversal' a 'FilePath' -> 'FilePath' -> m ()+-- ('</>=') :: 'MonadState' s m => 'Setter'' s 'FilePath' -> 'FilePath' -> m ()+-- ('</>=') :: 'MonadState' s m => 'Iso'' s 'FilePath' -> 'FilePath' -> m ()+-- ('</>=') :: 'MonadState' s m => 'Lens'' s 'FilePath' -> 'FilePath' -> m ()+-- ('</>=') :: 'MonadState' s m => 'Traversal'' s 'FilePath' -> 'FilePath' -> m () -- @-(</>=) :: MonadState a m => SimpleSetting a FilePath -> FilePath -> m ()+(</>=) :: MonadState s m => ASetter' s FilePath -> FilePath -> m () l </>= b = State.modify (l </>~ b) {-# INLINE (</>=) #-}  --- | Add a path onto the end of the target of a 'Lens' and return the result+-- | Add a path onto the end of the target of a t'Lens' and return the result -- -- When you do not need the result of the operation, ('</>~') is more flexible.-(<</>~) :: LensLike ((,)FilePath) a b FilePath FilePath -> FilePath -> a -> (FilePath, b)+(<</>~) :: LensLike ((,)FilePath) s a FilePath FilePath -> FilePath -> s -> (FilePath, a) l <</>~ m = l <%~ (</> m) {-# INLINE (<</>~) #-}  --- | Add a path onto the end of the target of a 'Lens' into+-- | Add a path onto the end of the target of a t'Lens' into -- your monad's state and return the result. -- -- When you do not need the result of the operation, ('</>=') is more flexible.-(<</>=) :: MonadState a m => SimpleLensLike ((,)FilePath) a FilePath -> FilePath -> m FilePath+(<</>=) :: MonadState s m => LensLike' ((,)FilePath) s FilePath -> FilePath -> m FilePath l <</>= r = l <%= (</> r) {-# INLINE (<</>=) #-}  --- | Modify the path by adding extension.+-- | Add a path onto the end of the target of a t'Lens' and return the original+-- value. ----- >>> :m + Control.Lens--- >>> both <.>~ "!!!" $ ("hello","world")--- ("hello.!!!","world.!!!")+-- When you do not need the original value, ('</>~') is more flexible.+(<<</>~) :: Optical' (->) q ((,)FilePath) s FilePath -> FilePath -> q s (FilePath, s)+l <<</>~ b = l $ \a -> (a, a </> b)+{-# INLINE (<<</>~) #-}++-- | Add a path onto the end of a target of a t'Lens' into your monad's state+-- and return the old value. --+-- When you do not need the result of the operation, ('</>=') is more flexible.+(<<</>=) :: MonadState s m => LensLike' ((,)FilePath) s FilePath -> FilePath -> m FilePath+l <<</>= b = l %%= \a -> (a, a </> b)+{-# INLINE (<<</>=) #-}++-- | Modify the path by adding an extension.+--+-- >>> both <.>~ "txt" $ ("hello","world")+-- ("hello.txt","world.txt")+-- -- @--- ('<.>~') :: 'Setter' a b 'FilePath' 'FilePath' -> 'String' -> a -> b--- ('<.>~') :: 'Iso' a b 'FilePath' 'FilePath' -> 'String' -> a -> b--- ('<.>~') :: 'Lens' a b 'FilePath' 'FilePath' -> 'String' -> a -> b--- ('<.>~') :: 'Traversal' a b 'FilePath' 'FilePath' -> 'String' -> a -> b+-- ('<.>~') :: t'Setter' s a 'FilePath' 'FilePath' -> 'String' -> s -> a+-- ('<.>~') :: t'Iso' s a 'FilePath' 'FilePath' -> 'String' -> s -> a+-- ('<.>~') :: t'Lens' s a 'FilePath' 'FilePath' -> 'String' -> s -> a+-- ('<.>~') :: t'Traversal' s a 'FilePath' 'FilePath' -> 'String' -> s -> a -- @-(<.>~) :: Setting a b FilePath FilePath -> String -> a -> b+(<.>~) :: ASetter s a FilePath FilePath -> String -> s -> a l <.>~ n = over l (<.> n) {-# INLINE (<.>~) #-} ---- | Modify the target(s) of a 'Simple' 'Lens', 'Iso', 'Setter' or 'Traversal' by adding an extension.+-- | Modify the target(s) of a 'Lens'', 'Iso'', 'Setter'' or 'Traversal'' by adding an extension. --+-- >>> execState (both <.>= "txt") ("hello","world")+-- ("hello.txt","world.txt")+-- -- @--- ('<.>=') :: 'MonadState' a m => 'Simple' 'Setter' a 'FilePath' -> 'String' -> m ()--- ('<.>=') :: 'MonadState' a m => 'Simple' 'Iso' a 'FilePath' -> 'String' -> m ()--- ('<.>=') :: 'MonadState' a m => 'Simple' 'Lens' a 'FilePath' -> 'String' -> m ()--- ('<.>=') :: 'MonadState' a m => 'Simple' 'Traversal' a 'FilePath' -> 'String' -> m ()+-- ('<.>=') :: 'MonadState' s m => 'Setter'' s 'FilePath' -> 'String' -> m ()+-- ('<.>=') :: 'MonadState' s m => 'Iso'' s 'FilePath' -> 'String' -> m ()+-- ('<.>=') :: 'MonadState' s m => 'Lens'' s 'FilePath' -> 'String' -> m ()+-- ('<.>=') :: 'MonadState' s m => 'Traversal'' s 'FilePath' -> 'String' -> m () -- @-(<.>=) :: MonadState a m => SimpleSetting a FilePath -> String -> m ()+(<.>=) :: MonadState s m => ASetter' s FilePath -> String -> m () l <.>= b = State.modify (l <.>~ b) {-# INLINE (<.>=) #-} ---- | Add an extension onto the end of the target of a 'Lens' and return the result+-- | Add an extension onto the end of the target of a t'Lens' and return the result --+-- >>> _1 <<.>~ "txt" $ ("hello","world")+-- ("hello.txt",("hello.txt","world"))+-- -- When you do not need the result of the operation, ('<.>~') is more flexible.-(<<.>~) :: LensLike ((,)FilePath) a b FilePath FilePath -> String -> a -> (FilePath, b)+(<<.>~) :: LensLike ((,)FilePath) s a FilePath FilePath -> String -> s -> (FilePath, a) l <<.>~ m = l <%~ (<.> m) {-# INLINE (<<.>~) #-}  --- | Add an extension onto the end of the target of a 'Lens' into+-- | Add an extension onto the end of the target of a t'Lens' into -- your monad's state and return the result. --+-- >>> evalState (_1 <<.>= "txt") ("hello","world")+-- "hello.txt"+-- -- When you do not need the result of the operation, ('<.>=') is more flexible.-(<<.>=) :: MonadState a m => SimpleLensLike ((,)FilePath) a FilePath -> String -> m FilePath+(<<.>=) :: MonadState s m => LensLike' ((,)FilePath) s FilePath -> String -> m FilePath l <<.>= r = l <%= (<.> r) {-# INLINE (<<.>=) #-} +-- | Add an extension onto the end of the target of a t'Lens' but+-- return the old value+--+-- >>> _1 <<<.>~ "txt" $ ("hello","world")+-- ("hello",("hello.txt","world"))+--+-- When you do not need the old value, ('<.>~') is more flexible.+(<<<.>~) :: Optical' (->) q ((,)FilePath) s FilePath -> String -> q s (FilePath, s)+l <<<.>~ b = l $ \a -> (a, a <.> b)+{-# INLINE (<<<.>~) #-} --- | A lens reading and writing to the basename.+-- | Add an extension onto the end of the target of a t'Lens' into your monad's+-- state and return the old value. ----- >>> basename .~ "filename" $ "path/name.png"--- "path/filename.png"-basename :: Simple Lens FilePath FilePath+-- >>> runState (_1 <<<.>= "txt") ("hello","world")+-- ("hello",("hello.txt","world"))+--+-- When you do not need the old value, ('<.>=') is more flexible.+(<<<.>=) :: MonadState s m => LensLike' ((,)FilePath) s FilePath -> String -> m FilePath+l <<<.>= b = l %%= \a -> (a, a <.> b)+{-# INLINE (<<<.>=) #-}++-- | A t'Lens' for reading and writing to the basename+--+-- Note: This is /not/ a legal t'Lens' unless the outer 'FilePath' has both a directory+-- and filename component and the generated basenames are not null and contain no directory+-- separators.+--+-- >>> (basename .~ "filename" $ "path" </> "name.png") == "path" </> "filename.png"+-- True+basename :: Lens' FilePath FilePath basename f p = (<.> takeExtension p) . (takeDirectory p </>) <$> f (takeBaseName p) {-# INLINE basename #-}  --- | A lens reading and writing to the directory.+-- | A t'Lens' for reading and writing to the directory ----- >>> "long/path/name.txt" ^. directory--- "long/path"-directory :: Simple Lens FilePath FilePath+-- Note: this is /not/ a legal t'Lens' unless the outer 'FilePath' already has a directory component,+-- and generated directories are not null.+--+-- >>> (("long" </> "path" </> "name.txt") ^. directory) == "long" </> "path"+-- True+directory :: Lens' FilePath FilePath directory f p = (</> takeFileName p) <$> f (takeDirectory p) {-# INLINE directory #-}  --- | A lens reading and writing to the extension.+-- | A t'Lens' for reading and writing to the extension ----- >>> extension .~ ".png" $ "path/name.txt"--- "path/name.png"-extension :: Simple Lens FilePath FilePath+-- Note: This is /not/ a legal t'Lens', unless you are careful to ensure that generated+-- extension 'FilePath' components are either null or start with 'System.FilePath.extSeparator'+-- and do not contain any internal 'System.FilePath.extSeparator's.+--+-- >>> (extension .~ ".png" $ "path" </> "name.txt") == "path" </> "name.png"+-- True+extension :: Lens' FilePath FilePath extension f p = (n <.>) <$> f e  where   (n, e) = splitExtension p {-# INLINE extension #-}  --- | A lens reading and writing to the full filename.+-- | A t'Lens' for reading and writing to the full filename ----- >>> filename .~ "name.txt" $ "path/name.png"--- "path/name.txt"-filename :: Simple Lens FilePath FilePath+-- Note: This is /not/ a legal t'Lens', unless you are careful to ensure that generated+-- filename 'FilePath' components are not null and do not contain any+-- elements of 'System.FilePath.pathSeparators's.+--+-- >>> (filename .~ "name.txt" $ "path" </> "name.png") == "path" </> "name.txt"+-- True+filename :: Lens' FilePath FilePath filename f p = (takeDirectory p </>) <$> f (takeFileName p) {-# INLINE filename #-}
+ src/System/IO/Error/Lens.hs view
@@ -0,0 +1,118 @@+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+-----------------------------------------------------------------------------+-- |+-- Module      :  System.IO.Error.Lens+-- Copyright   :  (C) 2012-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  Rank2Types+--+----------------------------------------------------------------------------+module System.IO.Error.Lens where++import Control.Lens+import GHC.IO.Exception+import System.IO+import Foreign.C.Types++-- * IOException Lenses++-- | Where the error happened.+location :: Lens' IOException String+location f s = f (ioe_location s) <&> \e -> s { ioe_location = e }+{-# INLINE location #-}++-- | Error type specific information.+description :: Lens' IOException String+description f s = f (ioe_description s) <&> \e -> s { ioe_description = e }+{-# INLINE description #-}++-- | The handle used by the action flagging this error.+handle :: Lens' IOException (Maybe Handle)+handle f s = f (ioe_handle s) <&> \e -> s { ioe_handle = e }+{-# INLINE handle #-}++-- | 'fileName' the error is related to.+--+fileName :: Lens' IOException (Maybe FilePath)+fileName f s = f (ioe_filename s) <&> \e -> s { ioe_filename = e }+{-# INLINE fileName #-}++-- | 'errno' leading to this error, if any.+--+errno :: Lens' IOException (Maybe CInt)+errno f s = f (ioe_errno s) <&> \e -> s { ioe_errno = e }+{-# INLINE errno #-}++------------------------------------------------------------------------------+-- Error Types+------------------------------------------------------------------------------++-- | What type of error it is++errorType :: Lens' IOException IOErrorType+errorType f s = f (ioe_type s) <&> \e -> s { ioe_type = e }+{-# INLINE errorType #-}++-- * IOErrorType Prisms+--++_AlreadyExists :: Prism' IOErrorType ()+_AlreadyExists = only AlreadyExists++_NoSuchThing :: Prism' IOErrorType ()+_NoSuchThing = only NoSuchThing++_ResourceBusy :: Prism' IOErrorType ()+_ResourceBusy = only ResourceBusy++_ResourceExhausted :: Prism' IOErrorType ()+_ResourceExhausted = only ResourceExhausted++_EOF :: Prism' IOErrorType ()+_EOF = only EOF++_IllegalOperation :: Prism' IOErrorType ()+_IllegalOperation = only IllegalOperation++_PermissionDenied :: Prism' IOErrorType ()+_PermissionDenied = only PermissionDenied++_UserError :: Prism' IOErrorType ()+_UserError = only UserError++_UnsatisfiedConstraints :: Prism' IOErrorType ()+_UnsatisfiedConstraints = only UnsatisfiedConstraints++_SystemError :: Prism' IOErrorType ()+_SystemError = only SystemError++_ProtocolError :: Prism' IOErrorType ()+_ProtocolError = only ProtocolError++_OtherError :: Prism' IOErrorType ()+_OtherError = only OtherError++_InvalidArgument :: Prism' IOErrorType ()+_InvalidArgument = only InvalidArgument++_InappropriateType :: Prism' IOErrorType ()+_InappropriateType = only InappropriateType++_HardwareFault :: Prism' IOErrorType ()+_HardwareFault = only HardwareFault++_UnsupportedOperation :: Prism' IOErrorType ()+_UnsupportedOperation = only UnsupportedOperation++_TimeExpired :: Prism' IOErrorType ()+_TimeExpired = only TimeExpired++_ResourceVanished :: Prism' IOErrorType ()+_ResourceVanished = only ResourceVanished++_Interrupted :: Prism' IOErrorType ()+_Interrupted = only Interrupted
+ tests/BigRecord.hs view
@@ -0,0 +1,65 @@+{-# LANGUAGE TemplateHaskell #-}++module BigRecord where++import Control.Lens++data Big = Big+  { _a0 :: Int , _a1 :: Int , _a2 :: Int , _a3 :: Int , _a4 :: Int , _a5 :: Int , _a6 :: Int , _a7 :: Int+  , _a8 :: Int , _a9 :: Int , _a10 :: Int , _a11 :: Int , _a12 :: Int , _a13 :: Int , _a14 :: Int , _a15 :: Int+  , _a16 :: Int , _a17 :: Int , _a18 :: Int , _a19 :: Int , _a20 :: Int , _a21 :: Int , _a22 :: Int , _a23 :: Int+  , _a24 :: Int , _a25 :: Int , _a26 :: Int , _a27 :: Int , _a28 :: Int , _a29 :: Int , _a30 :: Int , _a31 :: Int+  , _a32 :: Int , _a33 :: Int , _a34 :: Int , _a35 :: Int , _a36 :: Int , _a37 :: Int , _a38 :: Int , _a39 :: Int+  , _a40 :: Int , _a41 :: Int , _a42 :: Int , _a43 :: Int , _a44 :: Int , _a45 :: Int , _a46 :: Int , _a47 :: Int+  , _a48 :: Int , _a49 :: Int , _a50 :: Int , _a51 :: Int , _a52 :: Int , _a53 :: Int , _a54 :: Int , _a55 :: Int+  , _a56 :: Int , _a57 :: Int , _a58 :: Int , _a59 :: Int , _a60 :: Int , _a61 :: Int , _a62 :: Int , _a63 :: Int+  , _a64 :: Int , _a65 :: Int , _a66 :: Int , _a67 :: Int , _a68 :: Int , _a69 :: Int , _a70 :: Int , _a71 :: Int+  , _a72 :: Int , _a73 :: Int , _a74 :: Int , _a75 :: Int , _a76 :: Int , _a77 :: Int , _a78 :: Int , _a79 :: Int+  , _a80 :: Int , _a81 :: Int , _a82 :: Int , _a83 :: Int , _a84 :: Int , _a85 :: Int , _a86 :: Int , _a87 :: Int+  , _a88 :: Int , _a89 :: Int , _a90 :: Int , _a91 :: Int , _a92 :: Int , _a93 :: Int , _a94 :: Int , _a95 :: Int+  , _a96 :: Int , _a97 :: Int , _a98 :: Int , _a99 :: Int+  }++data Bigger = Bigger+  { _b0 :: Int , _b1 :: Int , _b2 :: Int , _b3 :: Int , _b4 :: Int , _b5 :: Int , _b6 :: Int , _b7 :: Int+  , _b8 :: Int , _b9 :: Int , _b10 :: Int , _b11 :: Int , _b12 :: Int , _b13 :: Int , _b14 :: Int , _b15 :: Int+  , _b16 :: Int , _b17 :: Int , _b18 :: Int , _b19 :: Int , _b20 :: Int , _b21 :: Int , _b22 :: Int , _b23 :: Int+  , _b24 :: Int , _b25 :: Int , _b26 :: Int , _b27 :: Int , _b28 :: Int , _b29 :: Int , _b30 :: Int , _b31 :: Int+  , _b32 :: Int , _b33 :: Int , _b34 :: Int , _b35 :: Int , _b36 :: Int , _b37 :: Int , _b38 :: Int , _b39 :: Int+  , _b40 :: Int , _b41 :: Int , _b42 :: Int , _b43 :: Int , _b44 :: Int , _b45 :: Int , _b46 :: Int , _b47 :: Int+  , _b48 :: Int , _b49 :: Int , _b50 :: Int , _b51 :: Int , _b52 :: Int , _b53 :: Int , _b54 :: Int , _b55 :: Int+  , _b56 :: Int , _b57 :: Int , _b58 :: Int , _b59 :: Int , _b60 :: Int , _b61 :: Int , _b62 :: Int , _b63 :: Int+  , _b64 :: Int , _b65 :: Int , _b66 :: Int , _b67 :: Int , _b68 :: Int , _b69 :: Int , _b70 :: Int , _b71 :: Int+  , _b72 :: Int , _b73 :: Int , _b74 :: Int , _b75 :: Int , _b76 :: Int , _b77 :: Int , _b78 :: Int , _b79 :: Int+  , _b80 :: Int , _b81 :: Int , _b82 :: Int , _b83 :: Int , _b84 :: Int , _b85 :: Int , _b86 :: Int , _b87 :: Int+  , _b88 :: Int , _b89 :: Int , _b90 :: Int , _b91 :: Int , _b92 :: Int , _b93 :: Int , _b94 :: Int , _b95 :: Int+  , _b96 :: Int , _b97 :: Int , _b98 :: Int , _b99 :: Int , _b100 :: Int , _b101 :: Int , _b102 :: Int , _b103 :: Int+  , _b104 :: Int , _b105 :: Int , _b106 :: Int , _b107 :: Int , _b108 :: Int , _b109 :: Int , _b110 :: Int , _b111 :: Int+  , _b112 :: Int , _b113 :: Int , _b114 :: Int , _b115 :: Int , _b116 :: Int , _b117 :: Int , _b118 :: Int , _b119 :: Int+  , _b120 :: Int , _b121 :: Int , _b122 :: Int , _b123 :: Int , _b124 :: Int , _b125 :: Int , _b126 :: Int , _b127 :: Int+  , _b128 :: Int , _b129 :: Int , _b130 :: Int , _b131 :: Int , _b132 :: Int , _b133 :: Int , _b134 :: Int , _b135 :: Int+  , _b136 :: Int , _b137 :: Int , _b138 :: Int , _b139 :: Int , _b140 :: Int , _b141 :: Int , _b142 :: Int , _b143 :: Int+  , _b144 :: Int , _b145 :: Int , _b146 :: Int , _b147 :: Int , _b148 :: Int , _b149 :: Int , _b150 :: Int , _b151 :: Int+  , _b152 :: Int , _b153 :: Int , _b154 :: Int , _b155 :: Int , _b156 :: Int , _b157 :: Int , _b158 :: Int , _b159 :: Int+  , _b160 :: Int , _b161 :: Int , _b162 :: Int , _b163 :: Int , _b164 :: Int , _b165 :: Int , _b166 :: Int , _b167 :: Int+  , _b168 :: Int , _b169 :: Int , _b170 :: Int , _b171 :: Int , _b172 :: Int , _b173 :: Int , _b174 :: Int , _b175 :: Int+  , _b176 :: Int , _b177 :: Int , _b178 :: Int , _b179 :: Int , _b180 :: Int , _b181 :: Int , _b182 :: Int , _b183 :: Int+  , _b184 :: Int , _b185 :: Int , _b186 :: Int , _b187 :: Int , _b188 :: Int , _b189 :: Int , _b190 :: Int , _b191 :: Int+  , _b192 :: Int , _b193 :: Int , _b194 :: Int , _b195 :: Int , _b196 :: Int , _b197 :: Int , _b198 :: Int , _b199 :: Int+  , _b200 :: Int , _b201 :: Int , _b202 :: Int , _b203 :: Int , _b204 :: Int , _b205 :: Int , _b206 :: Int , _b207 :: Int+  , _b208 :: Int , _b209 :: Int , _b210 :: Int , _b211 :: Int , _b212 :: Int , _b213 :: Int , _b214 :: Int , _b215 :: Int+  , _b216 :: Int , _b217 :: Int , _b218 :: Int , _b219 :: Int , _b220 :: Int , _b221 :: Int , _b222 :: Int , _b223 :: Int+  , _b224 :: Int , _b225 :: Int , _b226 :: Int , _b227 :: Int , _b228 :: Int , _b229 :: Int , _b230 :: Int , _b231 :: Int+  , _b232 :: Int , _b233 :: Int , _b234 :: Int , _b235 :: Int , _b236 :: Int , _b237 :: Int , _b238 :: Int , _b239 :: Int+  , _b240 :: Int , _b241 :: Int , _b242 :: Int , _b243 :: Int , _b244 :: Int , _b245 :: Int , _b246 :: Int , _b247 :: Int+  , _b248 :: Int , _b249 :: Int , _b250 :: Int , _b251 :: Int , _b252 :: Int , _b253 :: Int , _b254 :: Int , _b255 :: Int+  , _b256 :: Int , _b257 :: Int , _b258 :: Int , _b259 :: Int , _b260 :: Int , _b261 :: Int , _b262 :: Int , _b263 :: Int+  , _b264 :: Int , _b265 :: Int , _b266 :: Int , _b267 :: Int , _b268 :: Int , _b269 :: Int , _b270 :: Int , _b271 :: Int+  , _b272 :: Int , _b273 :: Int , _b274 :: Int , _b275 :: Int , _b276 :: Int , _b277 :: Int , _b278 :: Int , _b279 :: Int+  , _b280 :: Int , _b281 :: Int , _b282 :: Int , _b283 :: Int , _b284 :: Int , _b285 :: Int , _b286 :: Int , _b287 :: Int+  , _b288 :: Int , _b289 :: Int , _b290 :: Int , _b291 :: Int , _b292 :: Int , _b293 :: Int , _b294 :: Int , _b295 :: Int+  , _b296 :: Int , _b297 :: Int , _b298 :: Int , _b299 :: Int+  }++makeLensesWith (lensRules & generateRecordSyntax .~ True) ''Big+makeLensesWith (lensRules & generateRecordSyntax .~ True) ''Bigger
+ tests/T1024.hs view
@@ -0,0 +1,31 @@+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TypeSynonymInstances #-}++-- | Test 'makeFieldsId', which requires NoFieldSelectors and+-- DuplicateRecordFields. This test consequently only works on GHC >= 9.2.+module T1024 where++import Control.Lens++data Taco = Taco+  { hardShell :: Bool+  , sauce :: Int+  , filling :: String+  }+data Burrito = Burrito+  { sauce :: Int+  , filling :: String+  }+makeFieldsId ''Taco+makeFieldsId ''Burrito++checkTacoHardShell :: Lens' Taco Bool+checkTacoHardShell = hardShell++checkBurritoFilling :: Lens' Burrito String+checkBurritoFilling = filling
+ tests/T799.hs view
@@ -0,0 +1,23 @@+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TypeFamilies #-}+-- | Test 'makeFields' on a field whose type has a data family. Unlike for+-- type families, for data families we do not generate type equality+-- constraints, as they are not needed to avoid the issue in #754.+--+-- This tests that the fix for #799 is valid by putting this in a module in+-- which UndecidableInstances is not enabled.+module T799 where++import Control.Lens++data family DF a+newtype instance DF Int = FooInt Int++data Bar = Bar { _barFoo :: DF Int }+makeFields ''Bar++checkBarFoo :: Lens' Bar (DF Int)+checkBarFoo = foo
+ tests/T917.hs view
@@ -0,0 +1,41 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}++#if __GLASGOW_HASKELL__ < 806+{-# LANGUAGE TypeInType #-}+#endif+module T917 where++import Control.Lens+import Data.Kind+import Data.Proxy++-- Like Data.Functor.Const, but redefined to ensure that it is poly-kinded+-- across all versions of GHC, not just 8.0++newtype Constant a (b :: k) = Constant a++data T917OneA (a :: k -> Type) (b :: k -> Type) = MkT917OneA+data T917OneB a b = MkT917OneB (T917OneA a (Const b))+$(makePrisms ''T917OneB)++data T917TwoA (a :: k -> Type) (b :: k -> Type) = MkT917TwoA+data T917TwoB a b = MkT917TwoB (T917TwoA a (Const b))+$(makeClassyPrisms ''T917TwoB)++data family   T917DataFam (a :: k)+data instance T917DataFam (a :: Type) = MkT917DataFam { _unT917DataFam :: Proxy a }+$(makeLenses 'MkT917DataFam)++data T917GadtOne (a :: k) where+  MkT917GadtOne :: T917GadtOne (a :: Type)+$(makePrisms ''T917GadtOne)++data T917GadtTwo (a :: k) where+  MkT917GadtTwo :: T917GadtTwo (a :: Type)+$(makePrisms ''T917GadtTwo)
+ tests/T972.hs view
@@ -0,0 +1,20 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE TemplateHaskell #-}++#if __GLASGOW_HASKELL__ < 806+{-# LANGUAGE TypeInType #-}+#endif+module T972 where++import Control.Lens+import Data.Proxy++newtype Arc s = Arc { _unArc :: Int }++data Direction = Negative | Positive+data Dart s = Dart { _arc :: Arc s, _direction :: Direction }+$(makeLenses ''Dart)++data Fancy k (a :: k) = MkFancy { _unFancy1 :: k, _unFancy2 :: Proxy a }+$(makeLenses ''Fancy)
tests/doctests.hs view
@@ -1,28 +1,19 @@+-----------------------------------------------------------------------------+-- |+-- Module      :  Main (doctests)+-- Copyright   :  (C) 2012-14 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  portable+--+-- This module exists to add dependencies+----------------------------------------------------------------------------- module Main where -import Test.DocTest-import System.Directory-import System.FilePath-import Control.Applicative-import Control.Monad-import Data.List- main :: IO ()-main = getSources >>= \sources -> doctest $-    "-isrc"-  : "-idist/build/autogen"-  : "-optP-include"-  : "-optPdist/build/autogen/cabal_macros.h"-  : sources--getSources :: IO [FilePath]-getSources = filter (isSuffixOf ".hs") <$> go "src"-  where-    go dir = do-      (dirs, files) <- getFilesAndDirectories dir-      (files ++) . concat <$> mapM go dirs--getFilesAndDirectories :: FilePath -> IO ([FilePath], [FilePath])-getFilesAndDirectories dir = do-  c <- map (dir </>) . filter (`notElem` ["..", "."]) <$> getDirectoryContents dir-  (,) <$> filterM doesDirectoryExist c <*> filterM doesFileExist c+main = do+    putStrLn "This test-suite exists only to add dependencies"+    putStrLn "To run doctests: "+    putStrLn "    cabal build all --enable-tests"+    putStrLn "    cabal-docspec"
tests/hunit.hs view
@@ -1,22 +1,42 @@+{-# OPTIONS_GHC -Wno-missing-signatures #-}+{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-}-module Main where -import Control.Lens-import Control.Monad.State-import Data.Char-import Data.List as List-import Data.List.Lens-import Data.Map as Map-import Test.Framework.Providers.HUnit-import Test.Framework.TH-import Test.Framework-import Test.HUnit-+-----------------------------------------------------------------------------+-- |+-- Module      :  Main (hunit)+-- Copyright   :  (C) 2012-14 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  portable+--+-- This module provides a simple hunit test suite for lens.+-- -- The code attempts to enumerate common use cases rather than give an example -- of each available lens function. The tests here merely scratch the surface -- of what is possible using the lens package; there are a great many use cases -- (and lens functions) that aren't covered.+-----------------------------------------------------------------------------+module Main (main) where +import Control.Lens+import Control.Monad.State+import Data.Char+import qualified Data.Text as StrictT+import qualified Data.Text.Lazy as LazyT+import qualified Data.ByteString as StrictB+import qualified Data.ByteString.Lazy as LazyB+import qualified Data.List as List+import qualified Data.Map as Map+import Data.Map (Map)+#if !(MIN_VERSION_base(4,11,0))+import Data.Monoid+#endif+import Test.Tasty (defaultMain, testGroup)+import Test.Tasty.HUnit ((@?=), testCase)++ data Point =   Point   { _x :: Int -- ^ X coordinate@@ -42,6 +62,9 @@  makeLenses ''Polygon +data Shape = SBox Box | SPolygon Polygon | SCircle Point Int | SVoid+makePrisms ''Shape+ origin =   Point { _x = 0, _y = 0 } @@ -56,8 +79,8 @@   { _points = [ Point { _x = 0, _y = 0 }               , Point { _x = 4, _y = 7 }               , Point { _x = 8, _y = 0 } ]-  , _labels = fromList [ (Point { _x = 0, _y = 0 }, "Origin")-                       , (Point { _x = 4, _y = 7 }, "Peak") ]+  , _labels = Map.fromList [ (Point { _x = 0, _y = 0 }, "Origin")+                           , (Point { _x = 4, _y = 7 }, "Peak") ]   , _box = Box { _low = Point { _x = 0, _y = 0 }                , _high = Point { _x = 8, _y = 7 } }   }@@ -80,85 +103,85 @@   where test = use $ points.to last.to (vectorFrom origin).x  case_write_record_field =-  (trig % box.high.y .~ 6)-    @?= trig { _box = (trig % _box)-               { _high = (trig % _box % _high)+  (trig & box.high.y .~ 6)+    @?= trig { _box = (trig & _box)+               { _high = (trig & _box & _high)                          { _y = 6 } } }  case_write_state_record_field = do-  let trig' = trig { _box = (trig % _box)-                            { _high = (trig % _box % _high)+  let trig' = trig { _box = (trig & _box)+                            { _high = (trig & _box & _high)                                       { _y = 6 } } }   runState test trig @?= ((), trig')   where     test = box.high.y .= 6  case_write_record_field_and_access_new_value =-  (trig % box.high.y <.~ 6)-    @?= (6, trig { _box = (trig % _box)-                          { _high = (trig % _box % _high)+  (trig & box.high.y <.~ 6)+    @?= (6, trig { _box = (trig & _box)+                          { _high = (trig & _box & _high)                                     { _y = 6 } } })  case_write_state_record_field_and_access_new_value = do-  let trig' = trig { _box = (trig % _box)-                            { _high = (trig % _box % _high)+  let trig' = trig { _box = (trig & _box)+                            { _high = (trig & _box & _high)                                       { _y = 6 } } }   runState test trig @?= (6, trig')   where     test = box.high.y <.= 6  case_write_record_field_and_access_old_value =-  (trig % box.high.y <<.~ 6)-    @?= (7, trig { _box = (trig % _box)-                          { _high = (trig % _box % _high)+  (trig & box.high.y <<.~ 6)+    @?= (7, trig { _box = (trig & _box)+                          { _high = (trig & _box & _high)                                     { _y = 6 } } })  case_write_state_record_field_and_access_old_value = do-  let trig' = trig { _box = (trig % _box)-                            { _high = (trig % _box % _high)+  let trig' = trig { _box = (trig & _box)+                            { _high = (trig & _box & _high)                                       { _y = 6 } } }   runState test trig @?= (7, trig')   where     test = box.high.y <<.= 6  case_modify_record_field =-  (trig % box.low.y %~ (+ 2))-    @?= trig { _box = (trig % _box)-                      { _low = (trig % _box % _low)-                               { _y = ((trig % _box % _low % _y) + 2) } } }+  (trig & box.low.y %~ (+ 2))+    @?= trig { _box = (trig & _box)+                      { _low = (trig & _box & _low)+                               { _y = ((trig & _box & _low & _y) + 2) } } }  case_modify_state_record_field = do-  let trig' = trig { _box = (trig % _box)-                            { _low = (trig % _box % _low)-                                     { _y = ((trig % _box % _low % _y) + 2) } } }+  let trig' = trig { _box = (trig & _box)+                            { _low = (trig & _box & _low)+                                     { _y = ((trig & _box & _low & _y) + 2) } } }   runState test trig @?= ((), trig')   where     test = box.low.y %= (+ 2)  case_modify_record_field_and_access_new_value =-  (trig % box.low.y <%~ (+ 2))-    @?= (2, trig { _box = (trig % _box)-                          { _low = (trig % _box % _low)-                                   { _y = ((trig % _box % _low % _y) + 2) } } })+  (trig & box.low.y <%~ (+ 2))+    @?= (2, trig { _box = (trig & _box)+                          { _low = (trig & _box & _low)+                                   { _y = ((trig & _box & _low & _y) + 2) } } })  case_modify_state_record_field_and_access_new_value = do-  let trig' = trig { _box = (trig % _box)-                            { _low = (trig % _box % _low)-                                     { _y = ((trig % _box % _low % _y) + 2) } } }+  let trig' = trig { _box = (trig & _box)+                            { _low = (trig & _box & _low)+                                     { _y = ((trig & _box & _low & _y) + 2) } } }   runState test trig @?= (2, trig')   where     test = box.low.y <%= (+ 2)  case_modify_record_field_and_access_old_value =-  (trig % box.low.y <<%~ (+ 2))-    @?= (0, trig { _box = (trig % _box)-                          { _low = (trig % _box % _low)-                                   { _y = ((trig % _box % _low % _y) + 2) } } })+  (trig & box.low.y <<%~ (+ 2))+    @?= (0, trig { _box = (trig & _box)+                          { _low = (trig & _box & _low)+                                   { _y = ((trig & _box & _low & _y) + 2) } } })  case_modify_state_record_field_and_access_old_value = do-  let trig' = trig { _box = (trig % _box)-                            { _low = (trig % _box % _low)-                                     { _y = ((trig % _box % _low % _y) + 2) } } }+  let trig' = trig { _box = (trig & _box)+                            { _low = (trig & _box & _low)+                                     { _y = ((trig & _box & _low & _y) + 2) } } }   runState test trig @?= (0, trig')   where     test = box.low.y <<%= (+ 2)@@ -168,96 +191,249 @@   where     test = box.high %%= modifyAndCompute     modifyAndCompute point =-      (point ^. x, point % y +~ 2)-    trig' = trig { _box = (trig % _box)-                            { _high = (trig % _box % _high)-                                      { _y = ((trig % _box % _high % _y) + 2) } } }+      (point ^. x, point & y +~ 2)+    trig' = trig { _box = (trig & _box)+                            { _high = (trig & _box & _high)+                                      { _y = ((trig & _box & _high & _y) + 2) } } }  case_increment_record_field =-  (trig % box.low.y +~ 1) -- And similarly for -~ *~ //~ ^~ ^^~ **~ ||~ &&~-    @?= trig { _box = (trig % _box)-                      { _low = (trig % _box % _low)-                               { _y = ((trig % _box % _low % _y) + 1) } } }+  (trig & box.low.y +~ 1) -- And similarly for -~ *~ //~ ^~ ^^~ **~ ||~ &&~+    @?= trig { _box = (trig & _box)+                      { _low = (trig & _box & _low)+                               { _y = ((trig & _box & _low & _y) + 1) } } }  case_increment_state_record_field =   runState test trig @?= ((), trig')   where     test = box.low.y += 1-    trig' = trig { _box = (trig % _box)-                   { _low = (trig % _box % _low)-                     { _y = ((trig % _box % _low % _y) + 1) } } }+    trig' = trig { _box = (trig & _box)+                   { _low = (trig & _box & _low)+                     { _y = ((trig & _box & _low & _y) + 1) } } }  case_append_to_record_field =-  (trig % points ++~ [ origin ])-    @?= trig { _points = (trig % _points) ++ [ origin ] }+  (trig & points <>~ [ origin ])+    @?= trig { _points = (trig & _points) <> [ origin ] }  case_append_to_state_record_field = do   runState test trig @?= ((), trig')   where-    test = points ++= [ origin ]-    trig' = trig { _points = (trig % _points) ++ [ origin ] }+    test = points <>= [ origin ]+    trig' = trig { _points = (trig & _points) <> [ origin ] }  case_append_to_record_field_and_access_new_value =-  (trig % points <++~ [ origin ])-    @?= (_points trig ++ [ origin ], trig { _points = (trig % _points) ++ [ origin ] })+  (trig & points <<>~ [ origin ])+    @?= (_points trig <> [ origin ], trig { _points = (trig & _points) <> [ origin ] })  case_append_to_state_record_field_and_access_new_value = do-  runState test trig @?= (_points trig ++ [ origin ], trig')+  runState test trig @?= (_points trig <> [ origin ], trig')   where-    test = points <++= [ origin ]-    trig' = trig { _points = (trig % _points) ++ [ origin ] }+    test = points <<>= [ origin ]+    trig' = trig { _points = (trig & _points) <> [ origin ] } +case_prepend_to_record_field =+  (trig & points <>:~ [ origin ])+    @?= trig { _points = [ origin ] <> (trig & _points) }++case_prepend_to_state_record_field = do+  runState test trig @?= ((), trig')+  where+    test = points <>:= [ origin ]+    trig' = trig { _points = [ origin ] <> (trig & _points) }++case_prepend_to_record_field_and_access_new_value =+  (trig & points <<>:~ [ origin ])+    @?= ([ origin ] <> _points trig, trig { _points = [ origin ] <> (trig & _points) })++case_prepend_to_state_record_field_and_access_new_value = do+  runState test trig @?= ([ origin ] <> _points trig, trig')+  where+    test = points <<>:= [ origin ]+    trig' = trig { _points = [ origin ] <> (trig & _points) }++case_cons_to_record_field =+  (trig & points <|~ origin)+    @?= trig { _points = origin : (trig & _points) }++case_cons_to_state_record_field = do+  runState test trig @?= ((), trig')+  where+    test = points <|= origin+    trig' = trig { _points = origin : (trig & _points) }++case_cons_to_record_field_and_access_new_value =+  (trig & points <<|~ origin)+    @?= (origin : _points trig, trig { _points = origin : (trig & _points) })++case_cons_to_state_record_field_and_access_new_value =+  runState test trig @?= ([ origin ] <> _points trig, trig')+  where+    test = points <<|= origin+    trig' = trig { _points = origin : (trig & _points) }++case_snoc_to_record_field =+  (trig & points |>~ origin)+    @?= trig { _points = (trig & _points) `snoc` origin }++case_snoc_to_state_record_field = do+  runState test trig @?= ((), trig')+  where+    test = points |>= origin+    trig' = trig { _points = (trig & _points) `snoc` origin }++case_snoc_to_record_field_and_access_new_value =+  (trig & points <|>~ origin)+    @?= (_points trig `snoc` origin, trig { _points = (trig & _points) `snoc` origin })++case_snoc_to_state_record_field_and_access_new_value =+  runState test trig @?= (_points trig <> [ origin ], trig')+  where+    test = points <|>= origin+    trig' = trig { _points = (trig & _points) `snoc` origin }+ case_append_to_record_field_and_access_old_value =-  (trig % points <<%~ (++[origin]))-    @?= (_points trig, trig { _points = (trig % _points) ++ [ origin ] })+  (trig & points <<<>~ [ origin ])+    @?= (_points trig, trig { _points = (trig & _points) <> [ origin ] })  case_append_to_state_record_field_and_access_old_value = do   runState test trig @?= (_points trig, trig')   where-    test = points <<%= (++[origin])-    trig' = trig { _points = (trig % _points) ++ [ origin ] }+    test = points <<<>= [ origin ]+    trig' = trig { _points = (trig & _points) <> [ origin ] } +case_cons_to_record_field_and_access_old_value =+  (trig & points <<<|~ origin)+    @?= (_points trig, trig { _points = origin : (trig & _points) })++case_cons_to_state_record_field_and_access_old_value =+  runState test trig @?= (_points trig, trig')+  where+    test = points <<<|= origin+    trig' = trig { _points = origin : (trig & _points) }++case_snoc_to_record_field_and_access_old_value =+  (trig & points <<|>~ origin)+    @?= (_points trig, trig { _points = (trig & _points) `snoc` origin })++case_snoc_to_state_record_field_and_access_old_value =+  runState test trig @?= (_points trig, trig')+  where+    test = points <<|>= origin+    trig' = trig { _points = (trig & _points) `snoc` origin }+ case_read_maybe_map_entry = trig^.labels.at origin @?= Just "Origin"  case_read_maybe_state_map_entry =   runState test trig @?= (Just "Origin", trig)   where test = use $ labels.at origin -case_read_map_entry = trig^.labels.traverseAt origin @?= "Origin"+case_read_map_entry = trig^.labels.ix origin @?= "Origin"  case_read_state_map_entry = runState test trig @?= ("Origin", trig)-  where test = use $ labels.traverseAt origin+  where test = use $ labels.ix origin  case_modify_map_entry =-  (trig % labels.traverseAt origin %~ List.map toUpper)-    @?= trig { _labels = fromList [ (Point { _x = 0, _y = 0 }, "ORIGIN")-                                  , (Point { _x = 4, _y = 7 }, "Peak") ] }+  (trig & labels.ix origin %~ List.map toUpper)+    @?= trig { _labels = Map.fromList [ (Point { _x = 0, _y = 0 }, "ORIGIN")+                                      , (Point { _x = 4, _y = 7 }, "Peak") ] }  case_insert_maybe_map_entry =-  (trig % labels.at (Point { _x = 8, _y = 0 }) .~ Just "Right")-    @?= trig { _labels = fromList [ (Point { _x = 0, _y = 0 }, "Origin")-                                  , (Point { _x = 4, _y = 7 }, "Peak")-                                  , (Point { _x = 8, _y = 0 }, "Right") ] }+  (trig & labels.at (Point { _x = 8, _y = 0 }) .~ Just "Right")+    @?= trig { _labels = Map.fromList [ (Point { _x = 0, _y = 0 }, "Origin")+                                      , (Point { _x = 4, _y = 7 }, "Peak")+                                      , (Point { _x = 8, _y = 0 }, "Right") ] }  case_delete_maybe_map_entry =-  (trig % labels.at origin .~ Nothing)-    @?= trig { _labels = fromList [ (Point { _x = 4, _y = 7 }, "Peak") ] }+  (trig & labels.at origin .~ Nothing)+    @?= trig { _labels = Map.fromList [ (Point { _x = 4, _y = 7 }, "Peak") ] }  case_read_list_entry =-  (trig^.points.element 0)-    @?= origin+  (trig ^? points.element 0)+    @?= Just origin  case_write_list_entry =-  (trig % points.element 0 .~ Point { _x = 2, _y = 0 })+  (trig & points.element 0 .~ Point { _x = 2, _y = 0 })     @?= trig { _points = [ Point { _x = 2, _y = 0 }                          , Point { _x = 4, _y = 7 }                          , Point { _x = 8, _y = 0 } ] }  case_write_through_list_entry =-  (trig % points.element 0 . x .~ 2)+  (trig & points.element 0 . x .~ 2)     @?= trig { _points = [ Point { _x = 2, _y = 0 }                          , Point { _x = 4, _y = 7 }                          , Point { _x = 8, _y = 0 } ] } +case_correct_indexing_strict_text =+  map (\i -> StrictT.pack "12" ^? ix i) [-1..2]+    @?= [Nothing, Just '1', Just '2', Nothing]++case_correct_indexing_lazy_text =+  map (\i -> LazyT.pack "12" ^? ix i) [-1..2]+    @?= [Nothing, Just '1', Just '2', Nothing]++case_correct_indexing_strict_bytestring =+  map (\i -> StrictB.pack [1,2] ^? ix i) [-1..2]+    @?= [Nothing, Just 1, Just 2, Nothing]++case_correct_indexing_lazy_bytestring =+  map (\i -> LazyB.pack [1,2] ^? ix i) [-1..2]+    @?= [Nothing, Just 1, Just 2, Nothing]+ main :: IO ()-main = defaultMain [$testGroupGenerator]+main = defaultMain $+  testGroup "Main"+  [ testCase "read record field" case_read_record_field+  , testCase "read state record field" case_read_state_record_field+  , testCase "read record field and apply function" case_read_record_field_and_apply_function+  , testCase "read state record field and apply function" case_read_state_record_field_and_apply_function+  , testCase "write record field" case_write_record_field+  , testCase "write state record field" case_write_state_record_field+  , testCase "write record field and access new value" case_write_record_field_and_access_new_value+  , testCase "write state record field and access new value" case_write_state_record_field_and_access_new_value+  , testCase "write record field and access old value" case_write_record_field_and_access_old_value+  , testCase "write state record field and access old value" case_write_state_record_field_and_access_old_value+  , testCase "modify record field" case_modify_record_field+  , testCase "modify state record field" case_modify_state_record_field+  , testCase "modify record field and access new value" case_modify_record_field_and_access_new_value+  , testCase "modify state record field and access new value" case_modify_state_record_field_and_access_new_value+  , testCase "modify record field and access old value" case_modify_record_field_and_access_old_value+  , testCase "modify state record field and access old value" case_modify_state_record_field_and_access_old_value+  , testCase "modify record field and access side result" case_modify_record_field_and_access_side_result+  , testCase "increment record field" case_increment_record_field+  , testCase "increment state record field" case_increment_state_record_field+  , testCase "append to record field" case_append_to_record_field+  , testCase "append to state record field" case_append_to_state_record_field+  , testCase "prepend to record field" case_prepend_to_record_field+  , testCase "prepend to state record field" case_prepend_to_state_record_field+  , testCase "cons to record field" case_cons_to_record_field+  , testCase "cons to state record field" case_cons_to_state_record_field+  , testCase "snoc to record field" case_snoc_to_record_field+  , testCase "snoc to state record field" case_snoc_to_state_record_field+  , testCase "append to record field and access new value" case_append_to_record_field_and_access_new_value+  , testCase "append to state record field and access new value" case_append_to_state_record_field_and_access_new_value+  , testCase "prepend to record field and access new value" case_prepend_to_record_field_and_access_new_value+  , testCase "prepend to state record field and access new value" case_prepend_to_state_record_field_and_access_new_value+  , testCase "cons to record field and access new value" case_cons_to_record_field_and_access_new_value+  , testCase "cons to state record field and access new value" case_cons_to_state_record_field_and_access_new_value+  , testCase "snoc to record field and access new value" case_snoc_to_record_field_and_access_new_value+  , testCase "snoc to state record field and access new value" case_snoc_to_state_record_field_and_access_new_value+  , testCase "append to record field and access old value" case_append_to_record_field_and_access_old_value+  , testCase "append to state record field and access old value" case_append_to_state_record_field_and_access_old_value+  , testCase "cons to record field and access old value" case_cons_to_record_field_and_access_old_value+  , testCase "cons to state record field and access old value" case_cons_to_state_record_field_and_access_old_value+  , testCase "snoc to record field and access old value" case_snoc_to_record_field_and_access_old_value+  , testCase "snoc to state record field and access old value" case_snoc_to_state_record_field_and_access_old_value+  , testCase "read maybe map entry" case_read_maybe_map_entry+  , testCase "read maybe state map entry" case_read_maybe_state_map_entry+  , testCase "read map entry" case_read_map_entry+  , testCase "read state map entry" case_read_state_map_entry+  , testCase "modify map entry" case_modify_map_entry+  , testCase "insert maybe map entry" case_insert_maybe_map_entry+  , testCase "delete maybe map entry" case_delete_maybe_map_entry+  , testCase "read list entry" case_read_list_entry+  , testCase "write list entry" case_write_list_entry+  , testCase "write through list entry" case_write_through_list_entry+  , testCase "correct indexing strict text" case_correct_indexing_strict_text+  , testCase "correct indexing lazy text" case_correct_indexing_lazy_text+  , testCase "correct indexing strict bytestring" case_correct_indexing_strict_bytestring+  , testCase "correct indexing lazy bytestring" case_correct_indexing_lazy_bytestring+  ]
tests/properties.hs view
@@ -1,90 +1,159 @@+{-# OPTIONS_GHC -Wno-missing-signatures #-}+{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-}-{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ExtendedDefaultRules #-}+{-# LANGUAGE LiberalTypeSynonyms #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE KindSignatures #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE ConstraintKinds #-}+-----------------------------------------------------------------------------+-- |+-- Module      :  Main (properties)+-- Copyright   :  (C) 2012-14 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-- This module provides a set of QuickCheck properties that can be run through+-- test-framework to validate a number of expected behaviors of the library.+----------------------------------------------------------------------------- module Main where -import Control.Applicative-import Control.Monad import Control.Lens-import Data.Functor.Identity-import System.Exit import Test.QuickCheck-import Test.QuickCheck.All-import Test.QuickCheck.Function-import Data.Text.Strict.Lens+import Test.Tasty (defaultMain, testGroup)+import Test.Tasty.QuickCheck (testProperty)+import Data.Char (isAlphaNum, isAscii, toUpper)+import qualified Data.Text.Strict.Lens as Text+import GHC.Exts (Constraint)+import Numeric (showHex, showOct, showSigned)+import Numeric.Lens+import Control.Lens.Properties (isIso, isLens, isPrism, isSetter, isTraversal) -setter_id :: Eq a => Simple Setter a b -> a -> Bool-setter_id l a = runIdentity (l Identity a) == a+#include "lens-common.h" -setter_composition :: Eq a => Simple Setter a b -> a -> Fun b b -> Fun b b -> Bool-setter_composition l a (Fun _ f) (Fun _ g) = mapOf l f (mapOf l g a) == mapOf l (f . g) a+-- an illegal lens+bad :: Lens' (Int,Int) Int+bad f (a,b) = (,) b <$> f a -lens_set_view :: Eq a => Simple Lens a b -> a -> Bool-lens_set_view l a = set l (view l a) a == a+badIso :: Iso' Int Bool+badIso = iso even fromEnum -lens_view_set :: Eq b => Simple Lens a b -> a -> b -> Bool-lens_view_set l a b = view l (set l b a) == b+-- Control.Lens.Type+prop_1                               = isLens (_1 :: Lens' (Int,Double,()) Int)+prop_2                               = isLens (_2 :: Lens' (Int,Bool) Bool)+prop_3                               = isLens (_3 :: Lens' (Int,Bool,()) ())+prop_4                               = isLens (_4 :: Lens' (Int,Bool,(),Maybe Int) (Maybe Int))+prop_5                               = isLens (_5 :: Lens' ((),(),(),(),Int) Int)+prop_6                               = isLens (_6 :: Lens' ((),(),(),(),Int,Bool) Bool)+prop_7                               = isLens (_7 :: Lens' ((),(),(),(),(),Int,Bool) Bool)+prop_8                               = isLens (_8 :: Lens' ((),(),(),(),(),(),Int,Bool) Bool)+prop_9                               = isLens (_9 :: Lens' ((),(),(),(),(),(),(),Int,Bool) Bool)+prop_10                               = isLens (_10 :: Lens' ((),(),(),(),(),(),(),(),Int,Bool) Bool) -setter_set_set :: Eq a => Simple Setter a b -> a -> b -> b -> Bool-setter_set_set l a b c = set l c (set l b a) == set l c a+prop_2_2                             = isLens (_2._2 :: Lens' (Int,(Int,Bool),Double) Bool) -iso_hither :: Eq a => Simple Iso a b -> a -> Bool-iso_hither l a = a ^.l.from l == a+-- prop_illegal_lens                    = expectFailure $ isLens bad+-- prop_illegal_traversal               = expectFailure $ isTraversal bad+-- prop_illegal_setter                  = expectFailure $ isSetter bad+-- prop_illegal_iso                     = expectFailure $ isIso badIso -iso_yon :: Eq b => Simple Iso a b -> b -> Bool-iso_yon l b = b^.from l.l == b+-- Control.Lens.Setter+prop_mapped                          = isSetter (mapped :: Setter' [Int] Int)+prop_mapped_mapped                   = isSetter (mapped.mapped :: Setter' [Maybe Int] Int) -isSetter :: (Arbitrary a, Arbitrary b, CoArbitrary b, Show a, Show b, Eq a, Function b)-         => Simple Setter a b -> Property-isSetter l = setter_id l .&. setter_composition l .&. setter_set_set l+prop_both                            = isTraversal (both           :: Traversal' (Int,Int) Int)+prop_traverseLeft                    = isTraversal (_Left          :: Traversal' (Either Int Bool) Int)+prop_traverseRight                   = isTraversal (_Right         :: Traversal' (Either Int Bool) Bool) -isTraversal :: (Arbitrary a, Arbitrary b, CoArbitrary b, Show a, Show b, Eq a, Function b)-         => Simple Traversal a b -> Property-isTraversal l = isSetter l+prop_simple                          = isIso (simple :: Iso' Int Int)+--prop_enum                            = isIso (enum :: Iso' Int Char) -isLens :: (Arbitrary a, Arbitrary b, CoArbitrary b, Show a, Show b, Eq a, Eq b, Function b)-       => Simple Lens a b -> Property-isLens l = lens_set_view l .&. lens_view_set l .&. isTraversal l+prop__Left                           = isPrism (_Left :: Prism' (Either Int Bool) Int)+prop__Right                          = isPrism (_Right :: Prism' (Either Int Bool) Bool)+prop__Just                           = isPrism (_Just :: Prism' (Maybe Int) Int) -isIso :: (Arbitrary a, Arbitrary b, CoArbitrary a, CoArbitrary b, Show a, Show b, Eq a, Eq b, Function a, Function b)-      => Simple Iso a b -> Property-isIso l = iso_hither l .&. iso_yon l .&. isLens l .&. isLens (from l)+-- Data.List.Lens+prop_prefixed s                      = isPrism (prefixed s :: Prism' String String) --- an illegal lens-bad :: Simple Lens (Int,Int) Int-bad f (a,b) = (,) b <$> f a+-- Data.Text.Lens+prop_text s                          = s^.Text.packed.from Text.packed == s+--prop_text                           = isIso packed -badIso :: Simple Iso Int Bool-badIso = iso even fromEnum+-- Numeric.Lens+prop_base_show (n :: Integer) =+  conjoin [ show n == n ^. re (base 10)+          , showSigned showOct 0 n "" == n ^. re (base 8)+          , showSigned showHex 0 n "" == n ^. re (base 16)+          ]+prop_base_read (n :: Integer) =+  conjoin [ show n ^? base 10 == Just n+          , showSigned showOct 0 n "" ^? base 8  == Just n+          , showSigned showHex 0 n "" ^? base 16 == Just n+          , map toUpper (showSigned showHex 0 n "") ^? base 16 == Just n+          ]+prop_base_readFail (s :: String) =+  forAll (choose (2,36)) $ \b ->+    not isValid ==> s ^? base b == (Nothing :: Maybe Integer)+  where+    isValid = (not . null) sPos && all isValidChar sPos+    sPos = case s of { ('-':s') -> s'; _ -> s }+    isValidChar c = isAscii c && isAlphaNum c --- Control.Lens.Type-prop_1                               = isLens (_1 :: Simple Lens (Int,Double,()) Int)-prop_2                               = isLens (_2 :: Simple Lens (Int,Bool) Bool)-prop_3                               = isLens (_3 :: Simple Lens (Int,Bool,()) ())-prop_4                               = isLens (_4 :: Simple Lens (Int,Bool,(),Maybe Int) (Maybe Int))-prop_5                               = isLens (_5 :: Simple Lens ((),(),(),(),Int) Int)+-- Things that should typecheck but that we don't need to run+data Foo (a :: Constraint) (b :: Constraint) where+  Foo :: Foo (Num Int) b -prop_2_2                             = isLens (_2._2 :: Simple Lens (Int,(Int,Bool),Double) Bool)+sampleExtremePoly :: Equality s t a b -> Foo a (Functor b) -> Foo s (Functor t)+sampleExtremePoly f foo = f foo -prop_illegal_lens                    = expectFailure $ isLens bad-prop_illegal_traversal               = expectFailure $ isTraversal bad-prop_illegal_setter                  = expectFailure $ isSetter bad-prop_illegal_iso                     = expectFailure $ isIso badIso+samplePolyEquality :: Equality Monad Identity Monad Identity+samplePolyEquality f = f --- Control.Lens.Setter-prop_mapped                          = isSetter (mapped :: Simple Setter [Int] Int)-prop_mapped_mapped                   = isSetter (mapped.mapped :: Simple Setter [Maybe Int] Int)+lessSimplePoly :: forall KVS(k1 k2) (a :: k1) (b :: k2) .+                  Equality a b a b+lessSimplePoly f = f -prop_both                            = isTraversal (both :: Simple Traversal (Int,Int) Int)-prop_value (Fun _ k :: Fun Int Bool) = isTraversal (value k :: Simple Traversal (Int,Int) Int)-prop_traverseLeft                    = isTraversal (traverseLeft :: Simple Traversal (Either Int Bool) Int)-prop_traverseRight                   = isTraversal (traverseRight:: Simple Traversal (Either Int Bool) Bool)+equalityAnEqualityPoly ::+       forall KVS(k1 k2) (s :: k1) (t :: k2) (a :: k1) (b :: k2) .+       Equality s t a b -> AnEquality s t a b+equalityAnEqualityPoly f = f --- Data.Text.Lens-prop_text s                          = s^.packed.from packed == s+equalityIso :: Equality s t a b -> Iso s t a b+equalityIso f = f + main :: IO ()-main = do-  b <- $quickCheckAll-  unless b $ exitWith (ExitFailure 1)+main = defaultMain $+  testGroup "Main"+  [ testProperty "1" prop_1+  , testProperty "2" prop_2+  , testProperty "3" prop_3+  , testProperty "4" prop_4+  , testProperty "5" prop_5+  , testProperty "6" prop_6+  , testProperty "7" prop_7+  , testProperty "8" prop_8+  , testProperty "9" prop_9+  , testProperty "10" prop_10+  , testProperty "2 2" prop_2_2+  , testProperty "mapped" prop_mapped+  , testProperty "mapped mapped" prop_mapped_mapped+  , testProperty "both" prop_both+  , testProperty "traverseLeft" prop_traverseLeft+  , testProperty "traverseRight" prop_traverseRight+  , testProperty "simple" prop_simple+  , testProperty " Left" prop__Left+  , testProperty " Right" prop__Right+  , testProperty " Just" prop__Just+  , testProperty "prefixed" prop_prefixed+  , testProperty "text" prop_text+  , testProperty "base show" prop_base_show+  , testProperty "base read" prop_base_read+  , testProperty "base readFail" prop_base_readFail+  ]
tests/templates.hs view
@@ -1,54 +1,99 @@ {-# LANGUAGE TemplateHaskell #-}--- | The commented code summarizes what will be auto-generated below+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE CPP #-}+-----------------------------------------------------------------------------+-- |+-- Module      :  Main (templates)+-- Copyright   :  (C) 2012-14 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  experimental+-- Portability :  non-portable+--+-- This test suite validates that we are able to generate usable lenses with+-- template haskell.+--+-- The commented code summarizes what will be auto-generated below+----------------------------------------------------------------------------- module Main where  import Control.Lens -- import Test.QuickCheck (quickCheck)---- newtype Foo a = Foo a--- makeIso ''Foo--- foo :: Iso a b (Foo a) (Foo b)+import BigRecord ()+import T799 ()+import T917 ()+import T972 ()  data Bar a b c = Bar { _baz :: (a, b) } makeLenses ''Bar--- baz :: Lens (Bar a b c) (Bar a' b' c) (a,b) (a',b') +checkBaz :: Iso (Bar a b c) (Bar a' b' c') (a, b) (a', b')+checkBaz = baz+ data Quux a b = Quux { _quaffle :: Int, _quartz :: Double } makeLenses ''Quux--- quaffle :: Lens (Quux a b) (Quux a' b') Int Int--- quartz :: Lens (Quux a b) (Quux a' b') Double Double +checkQuaffle :: Lens (Quux a b) (Quux a' b') Int Int+checkQuaffle = quaffle++checkQuartz :: Lens (Quux a b) (Quux a' b') Double Double+checkQuartz = quartz+ data Quark a = Qualified   { _gaffer :: a }              | Unqualified { _gaffer :: a, _tape :: a } makeLenses ''Quark--- gaffer :: Simple Lens (Quark a) a--- tape :: Simple Traversal (Quark a) a -data Hadron a b = Science { _a1 :: a, _a2 :: a, _b :: b }+checkGaffer :: Lens' (Quark a) a+checkGaffer = gaffer++checkTape :: Traversal' (Quark a) a+checkTape = tape++data Hadron a b = Science { _a1 :: a, _a2 :: a, _c :: b } makeLenses ''Hadron--- a1 :: Simple Lens (Hadron a b) a--- a2 :: Simple Lens (Hadron a b) a--- b :: Lens (Hadron a b) (Hadron a b') b b' +checkA1 :: Lens' (Hadron a b) a+checkA1 = a1++checkA2 :: Lens' (Hadron a b) a+checkA2 = a2++checkC :: Lens (Hadron a b) (Hadron a b') b b'+checkC = c+ data Perambulation a b   = Mountains { _terrain :: a, _altitude :: b }   | Beaches   { _terrain :: a, _dunes :: a } makeLenses ''Perambulation--- terrain :: Simple Lens (Perambulation a b) a--- altitude :: Traversal (Perambulation a b) (Parambulation a b') b b'--- dunes :: Simple Traversal (Perambulation a b) a++checkTerrain :: Lens' (Perambulation a b) a+checkTerrain = terrain++checkAltitude :: Traversal (Perambulation a b) (Perambulation a b') b b'+checkAltitude = altitude++checkDunes :: Traversal' (Perambulation a b) a+checkDunes = dunes+ makeLensesFor [("_terrain", "allTerrain"), ("_dunes", "allTerrain")] ''Perambulation--- allTerrain :: Traversal (Perambulation a b) (Perambulation a' b) a a' +checkAllTerrain :: Traversal (Perambulation a b) (Perambulation a' b) a a'+checkAllTerrain = allTerrain+ data LensCrafted a = Still { _still :: a }                    | Works { _still :: a } makeLenses ''LensCrafted--- still :: Lens (LensCrafted a) (LensCrafted b) a b -data Danger a = Zone { _highway :: a }-              | Twilight-makeLensesWith (partialLenses .~ True $ buildTraversals .~ False $ lensRules) ''Danger--- highway :: Lens (Danger a) (Danger a') a a'+checkStill :: Lens (LensCrafted a) (LensCrafted b) a b+checkStill = still  data Task a = Task   { taskOutput :: a -> IO ()@@ -58,24 +103,378 @@  makeLensesFor [("taskOutput", "outputLens"), ("taskState", "stateLens"), ("taskStop", "stopLens")] ''Task -data Mono = Mono { _monoFoo :: Int, _monoBar :: Int }+checkOutputLens :: Lens' (Task a) (a -> IO ())+checkOutputLens = outputLens++checkStateLens :: Lens' (Task a) a+checkStateLens = stateLens++checkStopLens :: Lens' (Task a) (IO ())+checkStopLens = stopLens++data Mono a = Mono { _monoFoo :: a, _monoBar :: Int } makeClassy ''Mono -- class HasMono t where --   mono :: Simple Lens t Mono -- instance HasMono Mono where --   mono = id--- monoFoo :: HasMono t => Simple Lens t Int--- monoBar :: HasMono t => Simple Lens t Int -data Nucleosis = Nucleosis { _nuclear :: Mono }+checkMono :: HasMono t a => Lens' t (Mono a)+checkMono = mono++checkMono' :: Lens' (Mono a) (Mono a)+checkMono' = mono++checkMonoFoo :: HasMono t a => Lens' t a+checkMonoFoo = monoFoo++checkMonoBar :: HasMono t a => Lens' t Int+checkMonoBar = monoBar++data Nucleosis = Nucleosis { _nuclear :: Mono Int } makeClassy ''Nucleosis -- class HasNucleosis t where --   nucleosis :: Simple Lens t Nucleosis -- instance HasNucleosis Nucleosis--- nuclear :: HasNucleosis t => Simple Lens t Mono -instance HasMono Nucleosis where+checkNucleosis :: HasNucleosis t => Lens' t Nucleosis+checkNucleosis = nucleosis++checkNucleosis' :: Lens' Nucleosis Nucleosis+checkNucleosis' = nucleosis++checkNuclear :: HasNucleosis t => Lens' t (Mono Int)+checkNuclear = nuclear++instance HasMono Nucleosis Int where   mono = nuclear++-- Dodek's example+data Foo = Foo { _fooX, _fooY :: Int }+makeClassy ''Foo++checkFoo :: HasFoo t => Lens' t Foo+checkFoo = foo++checkFoo' :: Lens' Foo Foo+checkFoo' = foo++checkFooX :: HasFoo t => Lens' t Int+checkFooX = fooX++checkFooY :: HasFoo t => Lens' t Int+checkFooY = fooY++data Dude a = Dude+    { dudeLevel        :: Int+    , dudeAlias        :: String+    , dudeLife         :: ()+    , dudeThing        :: a+    }+makeFields ''Dude++checkLevel :: HasLevel t a => Lens' t a+checkLevel = level++checkLevel' :: Lens' (Dude a) Int+checkLevel' = level++checkAlias :: HasAlias t a => Lens' t a+checkAlias = alias++checkAlias' :: Lens' (Dude a) String+checkAlias' = alias++checkLife :: HasLife t a => Lens' t a+checkLife = life++checkLife' :: Lens' (Dude a) ()+checkLife' = life++checkThing :: HasThing t a => Lens' t a+checkThing = thing++checkThing' :: Lens' (Dude a) a+checkThing' = thing++data Lebowski a = Lebowski+    { _lebowskiAlias    :: String+    , _lebowskiLife     :: Int+    , _lebowskiMansion  :: String+    , _lebowskiThing    :: Maybe a+    }+makeFields ''Lebowski++checkAlias2 :: Lens' (Lebowski a) String+checkAlias2 = alias++checkLife2 :: Lens' (Lebowski a) Int+checkLife2 = life++checkMansion :: HasMansion t a => Lens' t a+checkMansion = mansion++checkMansion' :: Lens' (Lebowski a) String+checkMansion' = mansion++checkThing2 :: Lens' (Lebowski a) (Maybe a)+checkThing2 = thing++type family Fam a+type instance Fam Int = String++data FamRec a = FamRec+  { _famRecThing :: Fam a+  , _famRecUniqueToFamRec :: Fam a+  }+makeFields ''FamRec++checkFamRecThing :: Lens' (FamRec a) (Fam a)+checkFamRecThing = thing++checkFamRecUniqueToFamRec :: Lens' (FamRec a) (Fam a)+checkFamRecUniqueToFamRec = uniqueToFamRec++checkFamRecView :: FamRec Int -> String+checkFamRecView = view thing++data AbideConfiguration a = AbideConfiguration+    { _acLocation       :: String+    , _acDuration       :: Int+    , _acThing          :: a+    }+makeLensesWith abbreviatedFields ''AbideConfiguration++checkLocation :: HasLocation t a => Lens' t a+checkLocation = location++checkLocation' :: Lens' (AbideConfiguration a) String+checkLocation' = location++checkDuration :: HasDuration t a => Lens' t a+checkDuration = duration++checkDuration' :: Lens' (AbideConfiguration a) Int+checkDuration' = duration++checkThing3 :: Lens' (AbideConfiguration a) a+checkThing3 = thing++dudeDrink :: String+dudeDrink      = (Dude 9 "El Duderino" () "white russian")      ^. thing+lebowskiCarpet :: Maybe String+lebowskiCarpet = (Lebowski "Mr. Lebowski" 0 "" (Just "carpet")) ^. thing+abideAnnoyance :: String+abideAnnoyance = (AbideConfiguration "the tree" 10 "the wind")  ^. thing++declareLenses [d|+  data Quark1 a = Qualified1   { gaffer1 :: a }+                | Unqualified1 { gaffer1 :: a, tape1 :: a }+  |]+-- data Quark1 a = Qualified1 a | Unqualified1 a a++checkGaffer1 :: Lens' (Quark1 a) a+checkGaffer1 = gaffer1++checkTape1 :: Traversal' (Quark1 a) a+checkTape1 = tape1++declarePrisms [d|+  data Exp = Lit Int | Var String | Lambda { bound::String, body::Exp }+  |]+-- data Exp = Lit Int | Var String | Lambda { bound::String, body::Exp }++checkLit :: Int -> Exp+checkLit = Lit++checkVar :: String -> Exp+checkVar = Var++checkLambda :: String -> Exp -> Exp+checkLambda = Lambda++check_Lit :: Prism' Exp Int+check_Lit = _Lit++check_Var :: Prism' Exp String+check_Var = _Var++check_Lambda :: Prism' Exp (String, Exp)+check_Lambda = _Lambda+++declarePrisms [d|+  data Banana = Banana Int String+  |]+-- data Banana = Banana Int String++check_Banana :: Iso' Banana (Int, String)+check_Banana = _Banana++cavendish :: Banana+cavendish = _Banana # (4, "Cavendish")++data family Family a b c++declareLenses [d|+  data instance Family Int (a, b) a = FamilyInt { fm0 :: (b, a), fm1 :: Int }+  |]+-- data instance Family Int (a, b) a = FamilyInt a b+checkFm0 :: Lens (Family Int (a, b) a) (Family Int (a', b') a') (b, a) (b', a')+checkFm0 = fm0++checkFm1 :: Lens' (Family Int (a, b) a) Int+checkFm1 = fm1++class Class a where+  data Associated a+  method :: a -> Int++declareLenses [d|+  instance Class Int where+    data Associated Int = AssociatedInt { mochi :: Double }+    method = id+  |]++-- instance Class Int where+--   data Associated Int = AssociatedInt Double+--   method = id++checkMochi :: Iso' (Associated Int) Double+checkMochi = mochi++declareFields [d|+  data DeclaredFields f a+    = DeclaredField1 { declaredFieldsA0 :: f a    , declaredFieldsB0 :: Int }+    | DeclaredField2 { declaredFieldsC0 :: String , declaredFieldsB0 :: Int }+    deriving (Show)+  |]++checkA0 :: HasA0 t a => Traversal' t a+checkA0 = a0++checkB0 :: HasB0 t a => Lens' t a+checkB0 = b0++checkC0 :: HasC0 t a => Traversal' t a+checkC0 = c0++checkA0' :: Traversal' (DeclaredFields f a) (f a)+checkA0' = a0++checkB0' :: Lens' (DeclaredFields f a) Int+checkB0' = b0++checkC0' :: Traversal' (DeclaredFields f a) String+checkC0' = c0++declareFields [d|+    data Aardvark = Aardvark { aardvarkAlbatross :: Int }+    data Baboon   = Baboon   { baboonAlbatross   :: Int }+  |]++checkAardvark :: Lens' Aardvark Int+checkAardvark = albatross++checkBaboon :: Lens' Baboon Int+checkBaboon = albatross++data Rank2Tests+  = C1 { _r2length :: forall a. [a] -> Int+       , _r2nub    :: forall a. Eq a => [a] -> [a]+       }+  | C2 { _r2length :: forall a. [a] -> Int }++makeLenses ''Rank2Tests++checkR2length :: Getter Rank2Tests ([a] -> Int)+checkR2length = r2length++checkR2nub :: Eq a => Fold Rank2Tests ([a] -> [a])+checkR2nub = r2nub++data PureNoFields = PureNoFieldsA | PureNoFieldsB { _pureNoFields :: Int }+makeLenses ''PureNoFields++data ReviewTest where ReviewTest :: a -> ReviewTest+makePrisms ''ReviewTest+++-- test FieldNamers++data CheckUnderscoreNoPrefixNamer = CheckUnderscoreNoPrefixNamer+                                    { _fieldUnderscoreNoPrefix :: Int }+makeLensesWith (lensRules & lensField .~ underscoreNoPrefixNamer ) ''CheckUnderscoreNoPrefixNamer+checkUnderscoreNoPrefixNamer :: Lens' CheckUnderscoreNoPrefixNamer Int+checkUnderscoreNoPrefixNamer = fieldUnderscoreNoPrefix++-- how can we test NOT generating a lens for some fields?++data CheckMappingNamer = CheckMappingNamer+                         { fieldMappingNamer :: String }+makeLensesWith (lensRules & lensField .~ (mappingNamer (return . ("hogehoge_" ++)))) ''CheckMappingNamer+checkMappingNamer :: Lens' CheckMappingNamer String+checkMappingNamer = hogehoge_fieldMappingNamer++data CheckLookingupNamer = CheckLookingupNamer+                           { fieldLookingupNamer :: Int }+makeLensesWith (lensRules & lensField .~ (lookingupNamer [("fieldLookingupNamer", "foobarFieldLookingupNamer")])) ''CheckLookingupNamer+checkLookingupNamer :: Lens' CheckLookingupNamer Int+checkLookingupNamer = foobarFieldLookingupNamer++data CheckUnderscoreNamer = CheckUnderscoreNamer+                            { _hogeprefix_fieldCheckUnderscoreNamer :: Int }+makeLensesWith (defaultFieldRules & lensField .~ underscoreNamer) ''CheckUnderscoreNamer+checkUnderscoreNamer :: Lens' CheckUnderscoreNamer Int+checkUnderscoreNamer = fieldCheckUnderscoreNamer++data CheckCamelCaseNamer = CheckCamelCaseNamer+                           { _checkCamelCaseNamerFieldCamelCaseNamer :: Int }+makeLensesWith (defaultFieldRules & lensField .~ camelCaseNamer) ''CheckCamelCaseNamer+checkCamelCaseNamer :: Lens' CheckCamelCaseNamer Int+checkCamelCaseNamer = fieldCamelCaseNamer++data CheckAbbreviatedNamer = CheckAbbreviatedNamer+                             { _hogeprefixFieldAbbreviatedNamer :: Int }+makeLensesWith (defaultFieldRules & lensField .~ abbreviatedNamer ) ''CheckAbbreviatedNamer+checkAbbreviatedNamer :: Lens' CheckAbbreviatedNamer Int+checkAbbreviatedNamer = fieldAbbreviatedNamer++-- Ensure that `makeClassyPrisms` doesn't generate a redundant catch-all case (#866)+data T866 = MkT866+$(makeClassyPrisms ''T866)++-- Ensure that `makeClassyPrisms` doesn't generate duplicate prism names for+-- data types that share a name with one of its constructors (#865)+data T865 = T865 | T865a | T865b T866+$(makeClassyPrisms ''T865)+instance AsT866 T865 where+  _T866 = __T865 . _T866++-- {make,declare}Wrapped test cases for ordinary data types+newtype T997A a = MkT997A a+$(makeWrapped ''T997A)++$(declareWrapped [d|+  newtype T997B b = MkT997B b+  |])++-- {make,declare}Wrapped test cases for data family instances (#997)+data family T997FamA a+newtype instance T997FamA a = MkT997FamA a+$(makeWrapped 'MkT997FamA)++$(declareWrapped [d|+  data family T997FamB b+  newtype instance T997FamB b = MkT997FamB b+  |])++-- Ensure that a data type defined in a TH quote can have a field whose type+-- references another data type defined in the same quote (#1032)+declareFields [d|+    data T1032A = T1032A { t1032ASubB :: T1032B }+    data T1032B = T1032B { t1032BB :: Int }+  |]  main :: IO () main = putStrLn "test/templates.hs: ok"