packages feed

ilist 0.3.1.0 → 0.4.0.0

raw patch · 9 files changed

+1133/−722 lines, 9 filesdep ~basesetup-changednew-uploader

Dependency ranges changed: base

Files

CHANGELOG.md view
@@ -1,15 +1,28 @@-# 0.3.1.0+# Changelog +`ilist` uses [PVP Versioning][1].+The changelog is available [on GitHub][2].++## 0.4.0.0 — Dec 26, 2019++* Support GHC-8.8, GHC-8.6, GHC-8.4, GHC-8.2. Drop older GHC versions support.+* Update maintenance info.++## 0.3.1.0+ * Added `ireplicateM` and `ireplicateM_`. -# 0.3.0.0+## 0.3.0.0  * `ifind` now returns the index alongside with the value (same as in `lens`). -# 0.2.0.0+## 0.2.0.0  * `izipWithM` and `izipWithM_` have been generalised from `Monad` to `Applicative` (which mimics what was done in base-4.9). -# 0.1.0.0+## 0.1.0.0  First release.++[1]: https://pvp.haskell.org+[2]: https://github.com/kowainik/ilist/releases
LICENSE view
@@ -1,30 +1,373 @@-Copyright (c) 2016, Artyom+Mozilla Public License Version 2.0+================================== -All rights reserved.+1. Definitions+-------------- -Redistribution and use in source and binary forms, with or without-modification, are permitted provided that the following conditions are met:+1.1. "Contributor"+    means each individual or legal entity that creates, contributes to+    the creation of, or owns Covered Software. -    * Redistributions of source code must retain the above copyright-      notice, this list of conditions and the following disclaimer.+1.2. "Contributor Version"+    means the combination of the Contributions of others (if any) used+    by a Contributor and that particular Contributor's Contribution. -    * 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.+1.3. "Contribution"+    means Covered Software of a particular Contributor. -    * Neither the name of Artyom nor the names of other-      contributors may be used to endorse or promote products derived-      from this software without specific prior written permission.+1.4. "Covered Software"+    means Source Code Form to which the initial Contributor has attached+    the notice in Exhibit A, the Executable Form of such Source Code+    Form, and Modifications of such Source Code Form, in each case+    including portions thereof. -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.+1.5. "Incompatible With Secondary Licenses"+    means++    (a) that the initial Contributor has attached the notice described+        in Exhibit B to the Covered Software; or++    (b) that the Covered Software was made available under the terms of+        version 1.1 or earlier of the License, but not also under the+        terms of a Secondary License.++1.6. "Executable Form"+    means any form of the work other than Source Code Form.++1.7. "Larger Work"+    means a work that combines Covered Software with other material, in+    a separate file or files, that is not Covered Software.++1.8. "License"+    means this document.++1.9. "Licensable"+    means having the right to grant, to the maximum extent possible,+    whether at the time of the initial grant or subsequently, any and+    all of the rights conveyed by this License.++1.10. "Modifications"+    means any of the following:++    (a) any file in Source Code Form that results from an addition to,+        deletion from, or modification of the contents of Covered+        Software; or++    (b) any new file in Source Code Form that contains any Covered+        Software.++1.11. "Patent Claims" of a Contributor+    means any patent claim(s), including without limitation, method,+    process, and apparatus claims, in any patent Licensable by such+    Contributor that would be infringed, but for the grant of the+    License, by the making, using, selling, offering for sale, having+    made, import, or transfer of either its Contributions or its+    Contributor Version.++1.12. "Secondary License"+    means either the GNU General Public License, Version 2.0, the GNU+    Lesser General Public License, Version 2.1, the GNU Affero General+    Public License, Version 3.0, or any later versions of those+    licenses.++1.13. "Source Code Form"+    means the form of the work preferred for making modifications.++1.14. "You" (or "Your")+    means an individual or a legal entity exercising rights under this+    License. For legal entities, "You" includes any entity that+    controls, is controlled by, or is under common control with You. For+    purposes of this definition, "control" means (a) the power, direct+    or indirect, to cause the direction or management of such entity,+    whether by contract or otherwise, or (b) ownership of more than+    fifty percent (50%) of the outstanding shares or beneficial+    ownership of such entity.++2. License Grants and Conditions+--------------------------------++2.1. Grants++Each Contributor hereby grants You a world-wide, royalty-free,+non-exclusive license:++(a) under intellectual property rights (other than patent or trademark)+    Licensable by such Contributor to use, reproduce, make available,+    modify, display, perform, distribute, and otherwise exploit its+    Contributions, either on an unmodified basis, with Modifications, or+    as part of a Larger Work; and++(b) under Patent Claims of such Contributor to make, use, sell, offer+    for sale, have made, import, and otherwise transfer either its+    Contributions or its Contributor Version.++2.2. Effective Date++The licenses granted in Section 2.1 with respect to any Contribution+become effective for each Contribution on the date the Contributor first+distributes such Contribution.++2.3. Limitations on Grant Scope++The licenses granted in this Section 2 are the only rights granted under+this License. No additional rights or licenses will be implied from the+distribution or licensing of Covered Software under this License.+Notwithstanding Section 2.1(b) above, no patent license is granted by a+Contributor:++(a) for any code that a Contributor has removed from Covered Software;+    or++(b) for infringements caused by: (i) Your and any other third party's+    modifications of Covered Software, or (ii) the combination of its+    Contributions with other software (except as part of its Contributor+    Version); or++(c) under Patent Claims infringed by Covered Software in the absence of+    its Contributions.++This License does not grant any rights in the trademarks, service marks,+or logos of any Contributor (except as may be necessary to comply with+the notice requirements in Section 3.4).++2.4. Subsequent Licenses++No Contributor makes additional grants as a result of Your choice to+distribute the Covered Software under a subsequent version of this+License (see Section 10.2) or under the terms of a Secondary License (if+permitted under the terms of Section 3.3).++2.5. Representation++Each Contributor represents that the Contributor believes its+Contributions are its original creation(s) or it has sufficient rights+to grant the rights to its Contributions conveyed by this License.++2.6. Fair Use++This License is not intended to limit any rights You have under+applicable copyright doctrines of fair use, fair dealing, or other+equivalents.++2.7. Conditions++Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted+in Section 2.1.++3. Responsibilities+-------------------++3.1. Distribution of Source Form++All distribution of Covered Software in Source Code Form, including any+Modifications that You create or to which You contribute, must be under+the terms of this License. You must inform recipients that the Source+Code Form of the Covered Software is governed by the terms of this+License, and how they can obtain a copy of this License. You may not+attempt to alter or restrict the recipients' rights in the Source Code+Form.++3.2. Distribution of Executable Form++If You distribute Covered Software in Executable Form then:++(a) such Covered Software must also be made available in Source Code+    Form, as described in Section 3.1, and You must inform recipients of+    the Executable Form how they can obtain a copy of such Source Code+    Form by reasonable means in a timely manner, at a charge no more+    than the cost of distribution to the recipient; and++(b) You may distribute such Executable Form under the terms of this+    License, or sublicense it under different terms, provided that the+    license for the Executable Form does not attempt to limit or alter+    the recipients' rights in the Source Code Form under this License.++3.3. Distribution of a Larger Work++You may create and distribute a Larger Work under terms of Your choice,+provided that You also comply with the requirements of this License for+the Covered Software. If the Larger Work is a combination of Covered+Software with a work governed by one or more Secondary Licenses, and the+Covered Software is not Incompatible With Secondary Licenses, this+License permits You to additionally distribute such Covered Software+under the terms of such Secondary License(s), so that the recipient of+the Larger Work may, at their option, further distribute the Covered+Software under the terms of either this License or such Secondary+License(s).++3.4. Notices++You may not remove or alter the substance of any license notices+(including copyright notices, patent notices, disclaimers of warranty,+or limitations of liability) contained within the Source Code Form of+the Covered Software, except that You may alter any license notices to+the extent required to remedy known factual inaccuracies.++3.5. Application of Additional Terms++You may choose to offer, and to charge a fee for, warranty, support,+indemnity or liability obligations to one or more recipients of Covered+Software. However, You may do so only on Your own behalf, and not on+behalf of any Contributor. You must make it absolutely clear that any+such warranty, support, indemnity, or liability obligation is offered by+You alone, and You hereby agree to indemnify every Contributor for any+liability incurred by such Contributor as a result of warranty, support,+indemnity or liability terms You offer. You may include additional+disclaimers of warranty and limitations of liability specific to any+jurisdiction.++4. Inability to Comply Due to Statute or Regulation+---------------------------------------------------++If it is impossible for You to comply with any of the terms of this+License with respect to some or all of the Covered Software due to+statute, judicial order, or regulation then You must: (a) comply with+the terms of this License to the maximum extent possible; and (b)+describe the limitations and the code they affect. Such description must+be placed in a text file included with all distributions of the Covered+Software under this License. Except to the extent prohibited by statute+or regulation, such description must be sufficiently detailed for a+recipient of ordinary skill to be able to understand it.++5. Termination+--------------++5.1. The rights granted under this License will terminate automatically+if You fail to comply with any of its terms. However, if You become+compliant, then the rights granted under this License from a particular+Contributor are reinstated (a) provisionally, unless and until such+Contributor explicitly and finally terminates Your grants, and (b) on an+ongoing basis, if such Contributor fails to notify You of the+non-compliance by some reasonable means prior to 60 days after You have+come back into compliance. Moreover, Your grants from a particular+Contributor are reinstated on an ongoing basis if such Contributor+notifies You of the non-compliance by some reasonable means, this is the+first time You have received notice of non-compliance with this License+from such Contributor, and You become compliant prior to 30 days after+Your receipt of the notice.++5.2. If You initiate litigation against any entity by asserting a patent+infringement claim (excluding declaratory judgment actions,+counter-claims, and cross-claims) alleging that a Contributor Version+directly or indirectly infringes any patent, then the rights granted to+You by any and all Contributors for the Covered Software under Section+2.1 of this License shall terminate.++5.3. In the event of termination under Sections 5.1 or 5.2 above, all+end user license agreements (excluding distributors and resellers) which+have been validly granted by You or Your distributors under this License+prior to termination shall survive termination.++************************************************************************+*                                                                      *+*  6. Disclaimer of Warranty                                           *+*  -------------------------                                           *+*                                                                      *+*  Covered Software is provided under this License on an "as is"       *+*  basis, without warranty of any kind, either expressed, implied, or  *+*  statutory, including, without limitation, warranties that the       *+*  Covered Software is free of defects, merchantable, fit for a        *+*  particular purpose or non-infringing. The entire risk as to the     *+*  quality and performance of the Covered Software is with You.        *+*  Should any Covered Software prove defective in any respect, You     *+*  (not any Contributor) assume the cost of any necessary servicing,   *+*  repair, or correction. This disclaimer of warranty constitutes an   *+*  essential part of this License. No use of any Covered Software is   *+*  authorized under this License except under this disclaimer.         *+*                                                                      *+************************************************************************++************************************************************************+*                                                                      *+*  7. Limitation of Liability                                          *+*  --------------------------                                          *+*                                                                      *+*  Under no circumstances and under no legal theory, whether tort      *+*  (including negligence), contract, or otherwise, shall any           *+*  Contributor, or anyone who distributes Covered Software as          *+*  permitted above, be liable to You for any direct, indirect,         *+*  special, incidental, or consequential damages of any character      *+*  including, without limitation, damages for lost profits, loss of    *+*  goodwill, work stoppage, computer failure or malfunction, or any    *+*  and all other commercial damages or losses, even if such party      *+*  shall have been informed of the possibility of such damages. This   *+*  limitation of liability shall not apply to liability for death or   *+*  personal injury resulting from such party's negligence to the       *+*  extent applicable law prohibits such limitation. Some               *+*  jurisdictions do not allow the exclusion or limitation of           *+*  incidental or consequential damages, so this exclusion and          *+*  limitation may not apply to You.                                    *+*                                                                      *+************************************************************************++8. Litigation+-------------++Any litigation relating to this License may be brought only in the+courts of a jurisdiction where the defendant maintains its principal+place of business and such litigation shall be governed by laws of that+jurisdiction, without reference to its conflict-of-law provisions.+Nothing in this Section shall prevent a party's ability to bring+cross-claims or counter-claims.++9. Miscellaneous+----------------++This License represents the complete agreement concerning the subject+matter hereof. If any provision of this License is held to be+unenforceable, such provision shall be reformed only to the extent+necessary to make it enforceable. Any law or regulation which provides+that the language of a contract shall be construed against the drafter+shall not be used to construe this License against a Contributor.++10. Versions of the License+---------------------------++10.1. New Versions++Mozilla Foundation is the license steward. Except as provided in Section+10.3, no one other than the license steward has the right to modify or+publish new versions of this License. Each version will be given a+distinguishing version number.++10.2. Effect of New Versions++You may distribute the Covered Software under the terms of the version+of the License under which You originally received the Covered Software,+or under the terms of any subsequent version published by the license+steward.++10.3. Modified Versions++If you create software not governed by this License, and you want to+create a new license for such software, you may create and use a+modified version of this License if you rename the license and remove+any references to the name of the license steward (except to note that+such modified license differs from this License).++10.4. Distributing Source Code Form that is Incompatible With Secondary+Licenses++If You choose to distribute Source Code Form that is Incompatible With+Secondary Licenses under the terms of this version of the License, the+notice described in Exhibit B of this License must be attached.++Exhibit A - Source Code Form License Notice+-------------------------------------------++  This Source Code Form is subject to the terms of the Mozilla Public+  License, v. 2.0. If a copy of the MPL was not distributed with this+  file, You can obtain one at http://mozilla.org/MPL/2.0/.++If it is not possible or desirable to put the notice in a particular+file, then You may include the notice in a location (such as a LICENSE+file in a relevant directory) where a recipient would be likely to look+for such a notice.++You may add additional accurate notices of copyright ownership.++Exhibit B - "Incompatible With Secondary Licenses" Notice+---------------------------------------------------------++  This Source Code Form is "Incompatible With Secondary Licenses", as+  defined by the Mozilla Public License, v. 2.0.
+ README.md view
@@ -0,0 +1,36 @@+# ilist++[![Travis](https://img.shields.io/travis/kowainik/ilist.svg?logo=travis)](http://travis-ci.org/kowainik/ilist)+[![AppVeyor](https://ci.appveyor.com/api/projects/status/github/kowainik/ilist?branch=master&svg=true)](https://ci.appveyor.com/project/kowainik/ilist)+[![Hackage](https://img.shields.io/hackage/v/ilist.svg?logo=haskell)](https://hackage.haskell.org/package/ilist)+[![Stackage LTS](http://stackage.org/package/ilist/badge/lts)](http://stackage.org/lts/package/ilist)+[![Stackage Nightly](http://stackage.org/package/ilist/badge/nightly)](http://stackage.org/nightly/package/ilist)+[![MPL-2.0 license](https://img.shields.io/badge/license-MPL--2.0-blue.svg)](https://github.com/kowainik/ilist/blob/master/LICENSE)++## What is this++This is a library with lots of list functions that are related to indices. It has often-reinvented `deleteAt`, `setAt`, etc, as well as indexed variants of functions from `Data.List` (e.g. `imap`, `ifilter`, `izipWith`). It has no dependencies, builds in about a second, and works on GHC from 7.4 to 8.0; the functions are [optimised](https://github.com/aelve/ilist/blob/master/lib/Data/List/Index.hs) and benchmarked (for instance, the `zip [0..]` idiom is usually twice as slow, and sometimes 20× as slow).++So, this library is intended to be the canonical place for index-related functions. You are encouraged to depend on this library instead of reinventing the functions, using `zip [0..]`, or using [lens](hackage.haskell.org/package/lens) when all you need is a simple `imap` or `ifoldr` (not to mention that lens variants are usually 2–10 times slower for lists).++## Why should you care++You shouldn't, actually. This is a small library, it won't change anyone's life, and if you care about speed you probably shouldn't be using lists anyway (unless you keep your fingers crossed and hope that fusion will kick in). So, consider it more of a public service announcement – “hey, just in case you ever need them, index-related functions live here”.++## Usage++Unfortunately, `Data.List.Indexed` was taken by [IndexedList](http://hackage.haskell.org/package/IndexedList), which implements such exciting things as “counted lists” and “conic lists”. Nope, I'm not bitter at all. Okay, maybe a bit, even tho it's completely unfair to [IndexedList](http://hackage.haskell.org/package/IndexedList). Anyway:++~~~ haskell+import Data.List.Index+~~~++And you can use functions from `Data.List` by prepending `i` to them. There's also `indexed :: [a] -> [(Int,a)]` and a family of functions for modifying the element at an index (`deleteAt`, `setAt`, `modifyAt`, `updateAt`, `insertAt`).++Watch out – `ifoldl` has the index as the *second* parameter of the function:++~~~ haskell+ifoldl :: (b -> Int -> a -> b) -> b -> [a] -> b+~~~++That's the same convention that [containers](http://hackage.haskell.org/package/containers) and [vector](http://hackage.haskell.org/package/vector) use. Other functions pass the index as the first argument, as expected.
− Setup.hs
@@ -1,2 +0,0 @@-import Distribution.Simple-main = defaultMain
bench/Functions.hs view
@@ -1,8 +1,6 @@-{-# LANGUAGE-MagicHash,-BangPatterns,-CPP-  #-}+{-# LANGUAGE MagicHash #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE CPP #-}   -- All these functions have to be in a separate module because otherwise@@ -92,7 +90,7 @@   where     go _ [] = return ()     go i (x:xs) = do-      f (I# i) x+      _ <- f (I# i) x       go (i +# 1#) xs {-# INLINE imapM__rec #-} @@ -252,7 +250,7 @@ izipWithM__rec f xs ys = go 0# xs ys   where     go i (a:as) (b:bs) = do-      f (I# i) a b+      _ <- f (I# i) a b       go (i +# 1#) as bs     go _ _ _ = return () {-# INLINE izipWithM__rec #-}
bench/Main.hs view
@@ -1,7 +1,5 @@-{-# LANGUAGE-BangPatterns,-MagicHash-  #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE MagicHash #-}   import Control.Monad.Trans.State.Lazy
ilist.cabal view
@@ -1,57 +1,87 @@+cabal-version:       2.4 name:                ilist-version:             0.3.1.0+version:             0.4.0.0 synopsis:            Optimised list functions for doing index-related things description:-  Optimised list functions for doing index-related things. They're faster than common idioms in all cases, they avoid <https://ghc.haskell.org/trac/ghc/ticket/12620 space leaks>, and sometimes they fuse better as well.-homepage:            http://github.com/aelve/ilist-bug-reports:         http://github.com/aelve/ilist/issues-license:             BSD3+  Optimised list functions for doing index-related things. They're+  faster than common idioms in all cases, they avoid+  <https://ghc.haskell.org/trac/ghc/ticket/12620 space leaks>, and+  sometimes they fuse better as well.+homepage:            http://github.com/kowainik/ilist+bug-reports:         http://github.com/kowainik/ilist/issues+license:             MPL-2.0 license-file:        LICENSE author:              Artyom-maintainer:          yom@artyom.me--- copyright:           +maintainer:          Kowainik <xrom.xkov@gmail.com>+copyright:           2016-2019 Artyom Kazak (BSD-3-Clause)+                     2019-2020 Kowainik (MPL-2.0) category:            List-tested-with:         GHC == 7.4.2, GHC == 7.6.3, GHC == 7.8.4, GHC == 7.10.3, GHC == 8.0.1 build-type:          Simple-extra-source-files:  CHANGELOG.md-cabal-version:       >=1.10+extra-doc-files:     README.md+                     CHANGELOG.md+tested-with:         GHC == 8.2.2+                     GHC == 8.4.4+                     GHC == 8.6.5+                     GHC == 8.8.1  source-repository head   type:                git-  location:            git://github.com/aelve/ilist.git+  location:            https://github.com/kowainik/ilist.git +common common-options+  build-depends:       base >= 4.10 && < 4.14++  ghc-options:         -Wall+                       -Wincomplete-uni-patterns+                       -Wincomplete-record-updates+                       -Wcompat+                       -Widentities+                       -Wredundant-constraints+                       -Wpartial-fields+                       -fhide-source-paths+                       -freverse-errors+  if impl(ghc >= 8.8.1)+    ghc-options:       -Wmissing-deriving-strategies+                       -Werror=missing-deriving-strategies++  default-language:    Haskell2010+  default-extensions:  DeriveGeneric+                       DerivingStrategies+                       GeneralizedNewtypeDeriving+                       InstanceSigs+                       LambdaCase+                       OverloadedStrings+                       RecordWildCards+                       ScopedTypeVariables+                       TypeApplications+ library+  import:              common-options+  hs-source-dirs:      src   exposed-modules:     Data.List.Index-  -- other-modules:       -  -- other-extensions:    -  build-depends:       base >=4.5 && <5-  ghc-options:         -O2 -Wall -fno-warn-unused-do-bind-  hs-source-dirs:      lib-  default-language:    Haskell2010+  ghc-options:         -O2  test-suite tests+  import:              common-options   type:                exitcode-stdio-1.0+  hs-source-dirs:      tests   main-is:             Main.hs-  build-depends:       base-                     , hspec+  build-depends:       hspec                      , ilist                      , transformers-  ghc-options:         -O2 -Wall -fno-warn-unused-do-bind-  hs-source-dirs:      tests-  default-language:    Haskell2010+  ghc-options:         -O2 -fno-warn-unused-do-bind  benchmark bench+  import:              common-options   type:                exitcode-stdio-1.0+  hs-source-dirs:      bench   main-is:             Main.hs   other-modules:       Functions-  build-depends:       base-                     , criterion+  build-depends:       criterion                      , ilist                      -- imapM_ is broken in 4.13.2                      , lens >= 4.13.2.1                      , loop                      , transformers                      , vector-  ghc-options:         -O2 -Wall -fno-warn-unused-do-bind-  hs-source-dirs:      bench-  default-language:    Haskell2010+  ghc-options:         -O2
− lib/Data/List/Index.hs
@@ -1,654 +0,0 @@-{-# LANGUAGE-CPP,-MagicHash,-ScopedTypeVariables,-BangPatterns-  #-}---{- |-Note: a lot of these functions are available for other types (in their respective packages):--  * @<http://hackage.haskell.org/package/vector/docs/Data-Vector.html Data.Vector>@ provides 'indexed' and lots of other functions beginning with “i”.--  * @<http://hackage.haskell.org/package/containers/docs/Data-Map-Lazy.html Data.Map>@ and @<http://hackage.haskell.org/package/containers/docs/Data-Sequence.html Data.Sequence>@ provide similar functions, but use a different naming convention (e.g. @<http://hackage.haskell.org/package/containers/docs/Data-Map-Lazy.html#v:mapWithKey mapWithKey>@ for maps and @<http://hackage.haskell.org/package/containers/docs/Data-Sequence.html#v:foldrWithIndex foldrWithIndex>@ for sequences).--  * <http://hackage.haskell.org/package/lens lens> provides several typeclasses for indexed functions that work on maps, lists, vectors, bytestrings, and so on (in @<http://hackage.haskell.org/package/lens/docs/Control-Lens-Indexed.html Control.Lens.Indexed>@), but unfortunately they are pretty slow for lists.--}-module Data.List.Index-(-  -- * Original functions-  indexed,-  deleteAt,-  setAt,-  modifyAt,-  updateAt,-  insertAt,--  -- * Adapted functions from "Data.List"-  -- $adapted--  -- ** Maps-  imap,-  imapM, imapM_,-  ifor, ifor_,-  -- ** Folds-  ifoldr, ifoldl, ifoldl',-  iall, iany, iconcatMap,-  -- ** Sublists-  ifilter, ipartition,-  itakeWhile, idropWhile,-  -- ** Zipping-  izipWith,-  izipWithM, izipWithM_,-  -- ** Search-  ifind,-  ifindIndex,-  ifindIndices,--  -- * Less commonly used functions--  -- ** Zipping-  izipWith3,-  izipWith4,-  izipWith5,-  izipWith6,-  izipWith7,--  -- ** Monadic functions-  iforM, iforM_,-  itraverse, itraverse_,-  ireplicateM, ireplicateM_,-  ifoldrM,-  ifoldlM,-  -  -- ** Folds-  ifoldMap,-  imapAccumR,-  imapAccumL,-)-where---#if __GLASGOW_HASKELL__ >= 710-import GHC.Base (oneShot)-#define ONE_SHOT oneShot-#else-#define ONE_SHOT-#endif--#if __GLASGOW_HASKELL__ < 710-import Control.Applicative-import Data.Traversable (sequenceA)-#endif--import Data.Foldable (sequenceA_)-import Data.Maybe-import Data.Monoid-import GHC.Exts--{- Left to do:--Functions-~~~~~~~~~--alterF or something?--iscanl-iscanl'-iscanl1-iscanr-iscanr1--iiterate?--backpermute?-minIndex/maxIndex?--}--{- |-'indexed' pairs each element with its index.-->>> indexed "hello"-[(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]--/Subject to fusion./--}-indexed :: [a] -> [(Int, a)]-indexed xs = go 0# xs-  where-    go i (a:as) = (I# i, a) : go (i +# 1#) as-    go _ _ = []-{-# NOINLINE [1] indexed #-}--indexedFB :: ((Int, a) -> t -> t) -> a -> (Int# -> t) -> Int# -> t-indexedFB c = \x cont i -> (I# i, x) `c` cont (i +# 1#)-{-# INLINE [0] indexedFB #-}--{-# RULES-"indexed"       [~1] forall xs.    indexed xs = build (\c n -> foldr (indexedFB c) (\_ -> n) xs 0#)-"indexedList"   [1]  forall xs.    foldr (indexedFB (:)) (\_ -> []) xs 0# = indexed xs-  #-}--{- |-'deleteAt' deletes the element at an index.--If the index is negative or exceeds list length, the original list will be returned.--}-deleteAt :: Int -> [a] -> [a]-deleteAt i ls-  | i < 0 = ls-  | otherwise = go i ls-  where-    go 0 (_:xs) = xs-    go n (x:xs) = x : go (n-1) xs-    go _ [] = []-{-# INLINE deleteAt #-}--{- |-'setAt' sets the element at the index.--If the index is negative or exceeds list length, the original list will be returned.--}-setAt :: Int -> a -> [a] -> [a]-setAt i a ls-  | i < 0 = ls-  | otherwise = go i ls-  where-    go 0 (_:xs) = a : xs-    go n (x:xs) = x : go (n-1) xs-    go _ [] = []-{-# INLINE setAt #-}--{- |-'modifyAt' applies a function to the element at the index.--If the index is negative or exceeds list length, the original list will be returned.--}-modifyAt :: Int -> (a -> a) -> [a] -> [a]-modifyAt i f ls-  | i < 0 = ls-  | otherwise = go i ls-  where-    go 0 (x:xs) = f x : xs-    go n (x:xs) = x : go (n-1) xs-    go _ [] = []-{-# INLINE modifyAt #-}--{- |-'updateAt' applies a function to the element at the index, and then either replaces the element or deletes it (if the function has returned 'Nothing').--If the index is negative or exceeds list length, the original list will be returned.--}-updateAt :: Int -> (a -> Maybe a) -> [a] -> [a]-updateAt i f ls-  | i < 0 = ls-  | otherwise = go i ls-  where-    go 0 (x:xs) = case f x of-      Nothing -> xs-      Just x' -> x' : xs-    go n (x:xs) = x : go (n-1) xs-    go _ [] = []-{-# INLINE updateAt #-}--{- |-'insertAt' inserts an element at the given position:--@-(insertAt i x xs) !! i == x-@--If the index is negative or exceeds list length, the original list will be returned. (If the index is equal to the list length, the insertion can be carried out.)--}-insertAt :: Int -> a -> [a] -> [a]-insertAt i a ls-  | i < 0 = ls-  | otherwise = go i ls-  where-    go 0 xs = a : xs-    go n (x:xs) = x : go (n-1) xs-    go _ [] = []-{-# INLINE insertAt #-}--{---David Feuer says that drop-like functions tend to have problems when implemented with folds: <http://ircbrowse.net/browse/haskell?id=22794495&timestamp=1463607633#t1463607633>. I haven't been able to observe this, but since Data.List defines drop/dropWhile/etc that don't fuse, let's do it here as well – just in case. The original version (that does fuse) is below.---- The plan is that if it does inline, it'll be fast; and if it doesn't--- inline, the former definition will be used and sharing will be preserved--- (i.e. if i == 0, it won't rebuild the whole list).-deleteAtFB :: Int -> (a -> t -> t) -> a -> (Int# -> t) -> Int# -> t-deleteAtFB (I# i) c = \x r k ->-  case k ==# i of-    0# -> x `c` r (k +# 1#)-    _  -> r (k +# 1#)-{-# INLINE [0] deleteAtFB #-}--{-# RULES-"deleteAt"       [~1] forall i xs.    deleteAt i xs = build (\c n -> foldr (deleteAtFB i c) (\_ -> n) xs 0#)-"deleteAtList"   [1]  forall i xs.    foldr (deleteAtFB i (:)) (\_ -> []) xs 0# = deleteAt i xs-  #-}---}--{- $adapted--These functions mimic their counterparts in "Data.List" – 'imap', for instance, works like 'map' but gives the index of the element to the modifying function.--Note that left folds have the index argument /after/ the accumulator argument – that's the convention adopted by containers and vector (but not lens).--}--{- |-/Subject to fusion./--}-imap :: (Int -> a -> b) -> [a] -> [b]-imap f ls = go 0# ls-  where-    go i (x:xs) = f (I# i) x : go (i +# 1#) xs-    go _ _ = []-{-# NOINLINE [1] imap #-}--imapFB-  :: (b -> t -> t) -> (Int -> a -> b) -> a -> (Int# -> t) -> Int# -> t-imapFB c f = \x r k -> f (I# k) x `c` r (k +# 1#)-{-# INLINE [0] imapFB #-}--{-# RULES-"imap"       [~1] forall f xs.    imap f xs = build (\c n -> foldr (imapFB c f) (\_ -> n) xs 0#)-"imapList"   [1]  forall f xs.    foldr (imapFB (:) f) (\_ -> []) xs 0# = imap f xs-  #-}--{--Note: we don't apply the *FB transformation to 'iconcatMap' because it uses 'ifoldr' instead of 'foldr', and 'ifoldr' might get inlined itself, and rewriting 'iconcatMap' with 'foldr' instead of 'ifoldr' is annoying. So, in theory it's a small optimisation possibility (in practice I'm not so sure, given that functions with 'build' don't seem to perform worse than functions without it).--}-iconcatMap :: (Int -> a -> [b]) -> [a] -> [b]-iconcatMap f xs = build $ \c n ->-  ifoldr (\i x b -> foldr c b (f i x)) n xs-{-# INLINE iconcatMap #-}--ifoldMap :: Monoid m => (Int -> a -> m) -> [a] -> m-ifoldMap p ls = foldr go (\_ -> mempty) ls 0#-  where go x r k = p (I# k) x <> r (k +# 1#)-{-# INLINE ifoldMap #-}--{- |-/Subject to fusion./--}-iall :: (Int -> a -> Bool) -> [a] -> Bool-iall p ls = foldr go (\_ -> True) ls 0#-  where go x r k = p (I# k) x && r (k +# 1#)-{-# INLINE iall #-}--{- |-/Subject to fusion./--}-iany :: (Int -> a -> Bool) -> [a] -> Bool-iany p ls = foldr go (\_ -> False) ls 0#-  where go x r k = p (I# k) x || r (k +# 1#)-{-# INLINE iany #-}--imapM :: Monad m => (Int -> a -> m b) -> [a] -> m [b]-imapM f as = ifoldr k (return []) as-  where-    k i a r = do-      x <- f i a-      xs <- r-      return (x:xs)-{-# INLINE imapM #-}--iforM :: Monad m => [a] -> (Int -> a -> m b) -> m [b]-iforM = flip imapM-{-# INLINE iforM #-}--itraverse :: Applicative m => (Int -> a -> m b) -> [a] -> m [b]-itraverse f as = ifoldr k (pure []) as-  where-    k i a r = (:) <$> f i a <*> r-{-# INLINE itraverse #-}--ifor :: Applicative m => [a] -> (Int -> a -> m b) -> m [b]-ifor = flip itraverse-{-# INLINE ifor #-}--{- |-/Subject to fusion./--}-imapM_ :: Monad m => (Int -> a -> m b) -> [a] -> m ()-imapM_ f as = ifoldr k (return ()) as-  where-    k i a r = f i a >> r-{-# INLINE imapM_ #-}--{- |-/Subject to fusion./--}-iforM_ :: Monad m => [a] -> (Int -> a -> m b) -> m ()-iforM_ = flip imapM_-{-# INLINE iforM_ #-}--{- |-/Subject to fusion./--}-itraverse_ :: Applicative m => (Int -> a -> m b) -> [a] -> m ()-itraverse_ f as = ifoldr k (pure ()) as-  where-    k i a r = f i a *> r-{-# INLINE itraverse_ #-}--{- |-/Subject to fusion./--}-ifor_ :: Applicative m => [a] -> (Int -> a -> m b) -> m ()-ifor_ = flip itraverse_-{-# INLINE ifor_ #-}--{- |-Perform a given action @n@ times. Behaves like @for_ [0..n-1]@, but avoids <https://ghc.haskell.org/trac/ghc/ticket/12620 space leaks>.--If you want more complicated loops (e.g. counting downwards), consider the <https://hackage.haskell.org/package/loop loop> package.--}-ireplicateM :: Applicative m => Int -> (Int -> m a) -> m [a]-ireplicateM cnt f = go 0-  where-    go !i | i >= cnt  = pure []-          | otherwise = (:) <$> f i <*> go (i + 1)-{-# INLINE ireplicateM #-}--{- |-NB. This function intentionally uses 'Monad' even though 'Applicative' is enough. That's because the @transformers@ package didn't have an optimized definition of ('*>') for 'StateT' prior to 0.5.3.0, so for a common case of 'StateT' this function would be 40 times slower with the 'Applicative' constraint.--}-ireplicateM_ :: Monad m => Int -> (Int -> m a) -> m ()-ireplicateM_ cnt f = if cnt > 0 then go 0 else return ()-  where-    -- this is 30% faster for Maybe than the simpler-    --     go i | i == cnt  = return ()-    --          | otherwise = f i >> go (i + 1)-    cnt_ = cnt-1-    go !i = if i == cnt_ then f i >> return () else f i >> go (i + 1)-{-# INLINE ireplicateM_ #-}---- Using unboxed ints here doesn't seem to result in any benefit-ifoldr :: (Int -> a -> b -> b) -> b -> [a] -> b-ifoldr f z xs = foldr (\x g i -> f i x (g (i+1))) (const z) xs 0-{-# INLINE ifoldr #-}--ifoldrM :: Monad m => (Int -> a -> b -> m b) -> b -> [a] -> m b-ifoldrM f z xs = ifoldr k (return z) xs-  where-    k i a r = f i a =<< r-{-# INLINE ifoldrM #-}--imapAccumR-  :: (acc -> Int -> x -> (acc, y))-  -> acc-  -> [x]-  -> (acc, [y])-imapAccumR f z xs =-  foldr (\x g i -> let (a, ys) = g (i+1)-                       (a', y) = f a i x-                   in  (a', y:ys))-        (const (z, [])) xs 0-{-# INLINE imapAccumR #-}--{---ifoldr1 :: (Int -> a -> a -> a) -> [a] -> a-ifoldr1 f = go 0#-  where go _ [x]    = x-        go i (x:xs) = f (I# i) x (go (i +# 1#) xs)-        go _ []     = errorEmptyList "ifoldr1"-{-# INLINE [0] ifoldr1 #-}---}--{- |-The index isn't the first argument of the function because that's the convention adopted by containers and vector (but not lens).--/Subject to fusion./--}-ifoldl :: forall a b. (b -> Int -> a -> b) -> b -> [a] -> b-ifoldl k z0 xs =-  foldr (\(v::a) (fn :: (Int, b) -> b) ->-          ONE_SHOT (\((!i)::Int, z::b) -> fn (i+1, k z i v)))-        (snd :: (Int, b) -> b)-        xs-        (0, z0)-{-# INLINE ifoldl #-}--{- |-/Subject to fusion./--}-ifoldl' :: forall a b. (b -> Int -> a -> b) -> b -> [a] -> b-ifoldl' k z0 xs =-  foldr (\(v::a) (fn :: (Int, b) -> b) ->-          ONE_SHOT (\((!i)::Int, z::b) -> z `seq` fn (i+1, k z i v)))-        (snd :: (Int, b) -> b)-        xs-        (0, z0)-{-# INLINE ifoldl' #-}--{- |-/Subject to fusion./--}-ifoldlM :: Monad m => (b -> Int -> a -> m b) -> b -> [a] -> m b-ifoldlM f z xs = ifoldl k (return z) xs-  where-    k a i r = do a' <- a; f a' i r-{-# INLINE ifoldlM #-}--imapAccumL-  :: (acc -> Int -> x -> (acc, y))-  -> acc-  -> [x]-  -> (acc, [y])-imapAccumL f z xs =-  foldr (\(x::a) (r :: (Int,acc) -> (acc,[y])) ->-          ONE_SHOT (\((!i)::Int, s::acc) ->-            let (s', y)   = f s i x-                (s'', ys) = r (i+1, s')-            in (s'', y:ys)))-        ((\(_, a) -> (a, [])) :: (Int,acc) -> (acc,[y]))-        xs-        (0, z)-{-# INLINE imapAccumL #-}--{---ifoldl1 :: (a -> Int -> a -> a) -> [a] -> a-ifoldl1 f (x:xs) = ifoldl f x xs-ifoldl1 _ []     = errorEmptyList "ifoldl1"--ifoldl1' :: (a -> Int -> a -> a) -> [a] -> a-ifoldl1' f (x:xs) = ifoldl' f x xs-ifoldl1' _ []     = errorEmptyList "ifoldl1'"---}--ifilter :: (Int -> a -> Bool) -> [a] -> [a]-ifilter p ls = go 0# ls-  where-    go i (x:xs) | p (I# i) x = x : go (i +# 1#) xs-                | otherwise  = go (i +# 1#) xs-    go _ _ = []-{-# NOINLINE [1] ifilter #-}--ifilterFB-  :: (a -> t -> t) -> (Int -> a -> Bool) -> a -> (Int# -> t) -> Int# -> t-ifilterFB c p = \x r k ->-  if p (I# k) x then x `c` r (k +# 1#) else r (k +# 1#)-{-# INLINE [0] ifilterFB #-}--{-# RULES-"ifilter"       [~1] forall p xs.    ifilter p xs = build (\c n -> foldr (ifilterFB c p) (\_ -> n) xs 0#)-"ifilterList"   [1]  forall p xs.    foldr (ifilterFB (:) p) (\_ -> []) xs 0# = ifilter p xs-  #-}--itakeWhile :: (Int -> a -> Bool) -> [a] -> [a]-itakeWhile p ls = go 0# ls-  where-    go i (x:xs) | p (I# i) x = x : go (i +# 1#) xs-                | otherwise  = []-    go _ _ = []-{-# NOINLINE [1] itakeWhile #-}--itakeWhileFB-  :: (a -> t -> t) -> (Int -> a -> Bool) -> t -> a -> (Int# -> t) -> Int# -> t-itakeWhileFB c p n = \x r k ->-  if p (I# k) x then x `c` r (k +# 1#) else n-{-# INLINE [0] itakeWhileFB #-}--{-# RULES-"itakeWhile"       [~1] forall p xs.    itakeWhile p xs = build (\c n -> foldr (itakeWhileFB c p n) (\_ -> n) xs 0#)-"itakeWhileList"   [1]  forall p xs.    foldr (itakeWhileFB (:) p []) (\_ -> []) xs 0# = itakeWhile p xs-  #-}--idropWhile :: (Int -> a -> Bool) -> [a] -> [a]-idropWhile p ls = go 0# ls-  where-    go i (x:xs) | p (I# i) x = go (i +# 1#) xs-                | otherwise  = x:xs-    go _ [] = []-{-# INLINE idropWhile #-}--ipartition :: (Int -> a -> Bool) -> [a] -> ([a],[a])-ipartition p xs = ifoldr (iselect p) ([],[]) xs-{-# INLINE ipartition #-}--iselect :: (Int -> a -> Bool) -> Int -> a -> ([a], [a]) -> ([a], [a])-iselect p i x ~(ts,fs) | p i x     = (x:ts,fs)-                       | otherwise = (ts, x:fs)--ifind :: (Int -> a -> Bool) -> [a] -> Maybe (Int, a)-ifind p ls = go 0# ls-  where-    go i (x:xs) | p (I# i) x = Just (I# i, x)-                | otherwise  = go (i +# 1#) xs-    go _ _ = Nothing-{-# INLINE ifind #-}--ifindIndex :: (Int -> a -> Bool) -> [a] -> Maybe Int-ifindIndex p = listToMaybe . ifindIndices p--ifindIndices :: (Int -> a -> Bool) -> [a] -> [Int]-ifindIndices p ls = go 0# ls-  where-    go _ [] = []-    go i (x:xs) | p (I# i) x = I# i : go (i +# 1#) xs-                | otherwise  = go (i +# 1#) xs-{-# NOINLINE [1] ifindIndices #-}--ifindIndicesFB-  :: (Int -> t -> t) -> (Int -> a -> Bool) -> a -> (Int# -> t) -> Int# -> t-ifindIndicesFB c p = \x r k ->-  if p (I# k) x then I# k `c` r (k +# 1#) else r (k +# 1#)-{-# INLINE [0] ifindIndicesFB #-}--{-# RULES-"ifindIndices"       [~1] forall p xs.    ifindIndices p xs = build (\c n -> foldr (ifindIndicesFB c p) (\_ -> n) xs 0#)-"ifindIndicesList"   [1]  forall p xs.    foldr (ifindIndicesFB (:) p) (\_ -> []) xs 0# = ifindIndices p xs-  #-}--{---errorEmptyList :: String -> a-errorEmptyList fun = error ("Data.List.Index." ++ fun ++ ": empty list")---}--{- |-/Subject to fusion in the first argument./--}-izipWith :: (Int -> a -> b -> c) -> [a] -> [b] -> [c]-izipWith fun xs ys = go 0# xs ys-  where-    go i (a:as) (b:bs) = fun (I# i) a b : go (i +# 1#) as bs-    go _ _ _ = []-{-# NOINLINE [1] izipWith #-}--izipWithFB-  :: (c -> t -> t) -> (Int -> a -> b -> c) -> a -> b -> (Int# -> t) -> Int# -> t-izipWithFB c fun = \x y cont i -> fun (I# i) x y `c` cont (i +# 1#)-{-# INLINE [0] izipWithFB #-}--{-# RULES-"izipWith"       [~1] forall f xs ys.    izipWith f xs ys = build (\c n -> foldr2 (izipWithFB c f) (\_ -> n) xs ys 0#)-"izipWithList"   [1]  forall f xs ys.    foldr2 (izipWithFB (:) f) (\_ -> []) xs ys 0# = izipWith f xs ys-  #-}---- Copied from GHC.List--foldr2 :: (a -> b -> c -> c) -> c -> [a] -> [b] -> c-foldr2 k z = go-  where-        go []    _ys     = z-        go _xs   []      = z-        go (x:xs) (y:ys) = k x y (go xs ys)-{-# INLINE [0] foldr2 #-}--foldr2_left :: (a -> b -> c -> d) -> d -> a -> ([b] -> c) -> [b] -> d-foldr2_left _k  z _x _r []     = z-foldr2_left  k _z  x  r (y:ys) = k x y (r ys)--{-# RULES-"foldr2/left"   forall k z ys (g::forall b.(a->b->b)->b->b) .-                  foldr2 k z (build g) ys = g (foldr2_left  k z) (\_ -> z) ys- #-}--izipWith3-  :: (Int -> a -> b -> c -> d)-  -> [a] -> [b] -> [c] -> [d]-izipWith3 fun = go 0#-  where-    go i (a:as) (b:bs) (c:cs) =-      fun (I# i) a b c : go (i +# 1#) as bs cs-    go _ _ _ _ = []-{-# INLINE izipWith3 #-}--izipWith4-  :: (Int -> a -> b -> c -> d -> e)-  -> [a] -> [b] -> [c] -> [d] -> [e]-izipWith4 fun = go 0#-  where-    go i (a:as) (b:bs) (c:cs) (d:ds) =-      fun (I# i) a b c d : go (i +# 1#) as bs cs ds-    go _ _ _ _ _ = []-{-# INLINE izipWith4 #-}--izipWith5-  :: (Int -> a -> b -> c -> d -> e -> f)-  -> [a] -> [b] -> [c] -> [d] -> [e] -> [f]-izipWith5 fun = go 0#-  where-    go i (a:as) (b:bs) (c:cs) (d:ds) (e:es) =-      fun (I# i) a b c d e : go (i +# 1#) as bs cs ds es-    go _ _ _ _ _ _ = []-{-# INLINE izipWith5 #-}--izipWith6-  :: (Int -> a -> b -> c -> d -> e -> f -> g)-  -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g]-izipWith6 fun = go 0#-  where-    go i (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) =-      fun (I# i) a b c d e f : go (i +# 1#) as bs cs ds es fs-    go _ _ _ _ _ _ _ = []-{-# INLINE izipWith6 #-}--izipWith7-  :: (Int -> a -> b -> c -> d -> e -> f -> g -> h)-  -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h]-izipWith7 fun = go 0#-  where-    go i (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs) =-      fun (I# i) a b c d e f g : go (i +# 1#) as bs cs ds es fs gs-    go _ _ _ _ _ _ _ _ = []-{-# INLINE izipWith7 #-}--izipWithM :: Applicative f => (Int -> a -> b -> f c) -> [a] -> [b] -> f [c]-izipWithM f as bs = sequenceA (izipWith f as bs)-{-# INLINE izipWithM #-}--izipWithM_ :: Applicative f => (Int -> a -> b -> f c) -> [a] -> [b] -> f ()-izipWithM_ f as bs = sequenceA_ (izipWith f as bs)-{-# INLINE izipWithM_ #-}
+ src/Data/List/Index.hs view
@@ -0,0 +1,649 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE MagicHash    #-}++{- |+Copyright:  (c) 2016-2019 Artyom Kazak+            (c) 2019-2020 Kowainik+SPDX-License-Identifier: MPL-2.0+Maintainer: Kowainik <xrom.xkov@gmail.com>++Note: a lot of these functions are available for other types (in their respective packages):++  * @<http://hackage.haskell.org/package/vector/docs/Data-Vector.html Data.Vector>@ provides 'indexed' and lots of other functions beginning with “i”.++  * @<http://hackage.haskell.org/package/containers/docs/Data-Map-Lazy.html Data.Map>@ and @<http://hackage.haskell.org/package/containers/docs/Data-Sequence.html Data.Sequence>@ provide similar functions, but use a different naming convention (e.g. @<http://hackage.haskell.org/package/containers/docs/Data-Map-Lazy.html#v:mapWithKey mapWithKey>@ for maps and @<http://hackage.haskell.org/package/containers/docs/Data-Sequence.html#v:foldrWithIndex foldrWithIndex>@ for sequences).++  * <http://hackage.haskell.org/package/lens lens> provides several typeclasses for indexed functions that work on maps, lists, vectors, bytestrings, and so on (in @<http://hackage.haskell.org/package/lens/docs/Control-Lens-Indexed.html Control.Lens.Indexed>@), but unfortunately they are pretty slow for lists.+-}++module Data.List.Index+    ( -- * Original functions+      indexed+    , deleteAt+    , setAt+    , modifyAt+    , updateAt+    , insertAt++      -- * Adapted functions from "Data.List"+      -- $adapted+      -- ** Maps+    , imap+    , imapM+    , imapM_+    , ifor+    , ifor_+      -- ** Folds+    , ifoldr+    , ifoldl+    , ifoldl'+    , iall+    , iany+    , iconcatMap+      -- ** Sublists+    , ifilter+    , ipartition+    , itakeWhile+    , idropWhile+      -- ** Zipping+    , izipWith+    , izipWithM+    , izipWithM_+      -- ** Search+    , ifind+    , ifindIndex+    , ifindIndices++      -- * Less commonly used functions+      -- ** Zipping+    , izipWith3+    , izipWith4+    , izipWith5+    , izipWith6+    , izipWith7+      -- ** Monadic functions+    , iforM+    , iforM_+    , itraverse+    , itraverse_+    , ireplicateM+    , ireplicateM_+    , ifoldrM+    , ifoldlM+      -- ** Folds+    , ifoldMap+    , imapAccumR+    , imapAccumL+    ) where++import Data.Foldable (sequenceA_)+import Data.Maybe (listToMaybe)+import Data.Semigroup (Semigroup ((<>)))+import GHC.Base (Int (..), Int#, build, oneShot, (+#))+++{- Left to do:++Functions+~~~~~~~~~++alterF or something?++iscanl+iscanl'+iscanl1+iscanr+iscanr1++iiterate?++backpermute?+minIndex/maxIndex?+-}++{- |+'indexed' pairs each element with its index.++>>> indexed "hello"+[(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]++/Subject to fusion./+-}+indexed :: [a] -> [(Int, a)]+indexed xs = go 0# xs+  where+    go i (a:as) = (I# i, a) : go (i +# 1#) as+    go _ _      = []+{-# NOINLINE [1] indexed #-}++indexedFB :: ((Int, a) -> t -> t) -> a -> (Int# -> t) -> Int# -> t+indexedFB c = \x cont i -> (I# i, x) `c` cont (i +# 1#)+{-# INLINE [0] indexedFB #-}++{-# RULES+"indexed"       [~1] forall xs.    indexed xs = build (\c n -> foldr (indexedFB c) (\_ -> n) xs 0#)+"indexedList"   [1]  forall xs.    foldr (indexedFB (:)) (\_ -> []) xs 0# = indexed xs+  #-}++{- |+'deleteAt' deletes the element at an index.++If the index is negative or exceeds list length, the original list will be returned.+-}+deleteAt :: Int -> [a] -> [a]+deleteAt i ls+  | i < 0 = ls+  | otherwise = go i ls+  where+    go 0 (_:xs) = xs+    go n (x:xs) = x : go (n-1) xs+    go _ []     = []+{-# INLINE deleteAt #-}++{- |+'setAt' sets the element at the index.++If the index is negative or exceeds list length, the original list will be returned.+-}+setAt :: Int -> a -> [a] -> [a]+setAt i a ls+  | i < 0 = ls+  | otherwise = go i ls+  where+    go 0 (_:xs) = a : xs+    go n (x:xs) = x : go (n-1) xs+    go _ []     = []+{-# INLINE setAt #-}++{- |+'modifyAt' applies a function to the element at the index.++If the index is negative or exceeds list length, the original list will be returned.+-}+modifyAt :: Int -> (a -> a) -> [a] -> [a]+modifyAt i f ls+  | i < 0 = ls+  | otherwise = go i ls+  where+    go 0 (x:xs) = f x : xs+    go n (x:xs) = x : go (n-1) xs+    go _ []     = []+{-# INLINE modifyAt #-}++{- |+'updateAt' applies a function to the element at the index, and then either replaces the element or deletes it (if the function has returned 'Nothing').++If the index is negative or exceeds list length, the original list will be returned.+-}+updateAt :: Int -> (a -> Maybe a) -> [a] -> [a]+updateAt i f ls+  | i < 0 = ls+  | otherwise = go i ls+  where+    go 0 (x:xs) = case f x of+      Nothing -> xs+      Just x' -> x' : xs+    go n (x:xs) = x : go (n-1) xs+    go _ [] = []+{-# INLINE updateAt #-}++{- |+'insertAt' inserts an element at the given position:++@+(insertAt i x xs) !! i == x+@++If the index is negative or exceeds list length, the original list will be returned. (If the index is equal to the list length, the insertion can be carried out.)+-}+insertAt :: Int -> a -> [a] -> [a]+insertAt i a ls+  | i < 0 = ls+  | otherwise = go i ls+  where+    go 0 xs     = a : xs+    go n (x:xs) = x : go (n-1) xs+    go _ []     = []+{-# INLINE insertAt #-}++{-++David Feuer says that drop-like functions tend to have problems when implemented with folds: <http://ircbrowse.net/browse/haskell?id=22794495&timestamp=1463607633#t1463607633>. I haven't been able to observe this, but since Data.List defines drop/dropWhile/etc that don't fuse, let's do it here as well – just in case. The original version (that does fuse) is below.++-- The plan is that if it does inline, it'll be fast; and if it doesn't+-- inline, the former definition will be used and sharing will be preserved+-- (i.e. if i == 0, it won't rebuild the whole list).+deleteAtFB :: Int -> (a -> t -> t) -> a -> (Int# -> t) -> Int# -> t+deleteAtFB (I# i) c = \x r k ->+  case k ==# i of+    0# -> x `c` r (k +# 1#)+    _  -> r (k +# 1#)+{-# INLINE [0] deleteAtFB #-}++{-# RULES+"deleteAt"       [~1] forall i xs.    deleteAt i xs = build (\c n -> foldr (deleteAtFB i c) (\_ -> n) xs 0#)+"deleteAtList"   [1]  forall i xs.    foldr (deleteAtFB i (:)) (\_ -> []) xs 0# = deleteAt i xs+  #-}++-}++{- $adapted++These functions mimic their counterparts in "Data.List" – 'imap', for instance, works like 'map' but gives the index of the element to the modifying function.++Note that left folds have the index argument /after/ the accumulator argument – that's the convention adopted by containers and vector (but not lens).+-}++{- |+/Subject to fusion./+-}+imap :: (Int -> a -> b) -> [a] -> [b]+imap f ls = go 0# ls+  where+    go i (x:xs) = f (I# i) x : go (i +# 1#) xs+    go _ _      = []+{-# NOINLINE [1] imap #-}++imapFB+  :: (b -> t -> t) -> (Int -> a -> b) -> a -> (Int# -> t) -> Int# -> t+imapFB c f = \x r k -> f (I# k) x `c` r (k +# 1#)+{-# INLINE [0] imapFB #-}++{-# RULES+"imap"       [~1] forall f xs.    imap f xs = build (\c n -> foldr (imapFB c f) (\_ -> n) xs 0#)+"imapList"   [1]  forall f xs.    foldr (imapFB (:) f) (\_ -> []) xs 0# = imap f xs+  #-}++{-+Note: we don't apply the *FB transformation to 'iconcatMap' because it uses 'ifoldr' instead of 'foldr', and 'ifoldr' might get inlined itself, and rewriting 'iconcatMap' with 'foldr' instead of 'ifoldr' is annoying. So, in theory it's a small optimisation possibility (in practice I'm not so sure, given that functions with 'build' don't seem to perform worse than functions without it).+-}+iconcatMap :: (Int -> a -> [b]) -> [a] -> [b]+iconcatMap f xs = build $ \c n ->+  ifoldr (\i x b -> foldr c b (f i x)) n xs+{-# INLINE iconcatMap #-}++ifoldMap :: (Semigroup m, Monoid m) => (Int -> a -> m) -> [a] -> m+ifoldMap p ls = foldr go (\_ -> mempty) ls 0#+  where go x r k = p (I# k) x <> r (k +# 1#)+{-# INLINE ifoldMap #-}++{- |+/Subject to fusion./+-}+iall :: (Int -> a -> Bool) -> [a] -> Bool+iall p ls = foldr go (\_ -> True) ls 0#+  where go x r k = p (I# k) x && r (k +# 1#)+{-# INLINE iall #-}++{- |+/Subject to fusion./+-}+iany :: (Int -> a -> Bool) -> [a] -> Bool+iany p ls = foldr go (\_ -> False) ls 0#+  where go x r k = p (I# k) x || r (k +# 1#)+{-# INLINE iany #-}++imapM :: Monad m => (Int -> a -> m b) -> [a] -> m [b]+imapM f as = ifoldr k (return []) as+  where+    k i a r = do+      x <- f i a+      xs <- r+      return (x:xs)+{-# INLINE imapM #-}++iforM :: Monad m => [a] -> (Int -> a -> m b) -> m [b]+iforM = flip imapM+{-# INLINE iforM #-}++itraverse :: Applicative m => (Int -> a -> m b) -> [a] -> m [b]+itraverse f as = ifoldr k (pure []) as+  where+    k i a r = (:) <$> f i a <*> r+{-# INLINE itraverse #-}++ifor :: Applicative m => [a] -> (Int -> a -> m b) -> m [b]+ifor = flip itraverse+{-# INLINE ifor #-}++{- |+/Subject to fusion./+-}+imapM_ :: Monad m => (Int -> a -> m b) -> [a] -> m ()+imapM_ f as = ifoldr k (return ()) as+  where+    k i a r = f i a >> r+{-# INLINE imapM_ #-}++{- |+/Subject to fusion./+-}+iforM_ :: Monad m => [a] -> (Int -> a -> m b) -> m ()+iforM_ = flip imapM_+{-# INLINE iforM_ #-}++{- |+/Subject to fusion./+-}+itraverse_ :: Applicative m => (Int -> a -> m b) -> [a] -> m ()+itraverse_ f as = ifoldr k (pure ()) as+  where+    k i a r = f i a *> r+{-# INLINE itraverse_ #-}++{- |+/Subject to fusion./+-}+ifor_ :: Applicative m => [a] -> (Int -> a -> m b) -> m ()+ifor_ = flip itraverse_+{-# INLINE ifor_ #-}++{- |+Perform a given action @n@ times. Behaves like @for_ [0..n-1]@, but avoids <https://ghc.haskell.org/trac/ghc/ticket/12620 space leaks>.++If you want more complicated loops (e.g. counting downwards), consider the <https://hackage.haskell.org/package/loop loop> package.+-}+ireplicateM :: Applicative m => Int -> (Int -> m a) -> m [a]+ireplicateM cnt f = go 0+  where+    go !i | i >= cnt  = pure []+          | otherwise = (:) <$> f i <*> go (i + 1)+{-# INLINE ireplicateM #-}++{- |+NB. This function intentionally uses 'Monad' even though 'Applicative' is enough. That's because the @transformers@ package didn't have an optimized definition of ('*>') for 'StateT' prior to 0.5.3.0, so for a common case of 'StateT' this function would be 40 times slower with the 'Applicative' constraint.+-}+ireplicateM_ :: Monad m => Int -> (Int -> m a) -> m ()+ireplicateM_ cnt f = if cnt > 0 then go 0 else return ()+  where+    -- this is 30% faster for Maybe than the simpler+    --     go i | i == cnt  = return ()+    --          | otherwise = f i >> go (i + 1)+    cnt_ = cnt-1+    go !i = if i == cnt_ then f i >> return () else f i >> go (i + 1)+{-# INLINE ireplicateM_ #-}++-- Using unboxed ints here doesn't seem to result in any benefit+ifoldr :: (Int -> a -> b -> b) -> b -> [a] -> b+ifoldr f z xs = foldr (\x g i -> f i x (g (i+1))) (const z) xs 0+{-# INLINE ifoldr #-}++ifoldrM :: Monad m => (Int -> a -> b -> m b) -> b -> [a] -> m b+ifoldrM f z xs = ifoldr k (return z) xs+  where+    k i a r = f i a =<< r+{-# INLINE ifoldrM #-}++imapAccumR+  :: (acc -> Int -> x -> (acc, y))+  -> acc+  -> [x]+  -> (acc, [y])+imapAccumR f z xs =+  foldr (\x g i -> let (a, ys) = g (i+1)+                       (a', y) = f a i x+                   in  (a', y:ys))+        (const (z, [])) xs 0+{-# INLINE imapAccumR #-}++{-++ifoldr1 :: (Int -> a -> a -> a) -> [a] -> a+ifoldr1 f = go 0#+  where go _ [x]    = x+        go i (x:xs) = f (I# i) x (go (i +# 1#) xs)+        go _ []     = errorEmptyList "ifoldr1"+{-# INLINE [0] ifoldr1 #-}++-}++{- |+The index isn't the first argument of the function because that's the convention adopted by containers and vector (but not lens).++/Subject to fusion./+-}+ifoldl :: forall a b. (b -> Int -> a -> b) -> b -> [a] -> b+ifoldl k z0 xs =+  foldr (\(v::a) (fn :: (Int, b) -> b) ->+          oneShot (\((!i)::Int, z::b) -> fn (i+1, k z i v)))+        (snd :: (Int, b) -> b)+        xs+        (0, z0)+{-# INLINE ifoldl #-}++{- |+/Subject to fusion./+-}+ifoldl' :: forall a b. (b -> Int -> a -> b) -> b -> [a] -> b+ifoldl' k z0 xs =+  foldr (\(v::a) (fn :: (Int, b) -> b) ->+          oneShot (\((!i)::Int, z::b) -> z `seq` fn (i+1, k z i v)))+        (snd :: (Int, b) -> b)+        xs+        (0, z0)+{-# INLINE ifoldl' #-}++{- |+/Subject to fusion./+-}+ifoldlM :: Monad m => (b -> Int -> a -> m b) -> b -> [a] -> m b+ifoldlM f z xs = ifoldl k (return z) xs+  where+    k a i r = do a' <- a; f a' i r+{-# INLINE ifoldlM #-}++imapAccumL+  :: (acc -> Int -> x -> (acc, y))+  -> acc+  -> [x]+  -> (acc, [y])+imapAccumL f z xs =+  foldr (\(x::a) (r :: (Int,acc) -> (acc,[y])) ->+          oneShot (\((!i)::Int, s::acc) ->+            let (s', y)   = f s i x+                (s'', ys) = r (i+1, s')+            in (s'', y:ys)))+        ((\(_, a) -> (a, [])) :: (Int,acc) -> (acc,[y]))+        xs+        (0, z)+{-# INLINE imapAccumL #-}++{-++ifoldl1 :: (a -> Int -> a -> a) -> [a] -> a+ifoldl1 f (x:xs) = ifoldl f x xs+ifoldl1 _ []     = errorEmptyList "ifoldl1"++ifoldl1' :: (a -> Int -> a -> a) -> [a] -> a+ifoldl1' f (x:xs) = ifoldl' f x xs+ifoldl1' _ []     = errorEmptyList "ifoldl1'"++-}++ifilter :: (Int -> a -> Bool) -> [a] -> [a]+ifilter p ls = go 0# ls+  where+    go i (x:xs) | p (I# i) x = x : go (i +# 1#) xs+                | otherwise  = go (i +# 1#) xs+    go _ _ = []+{-# NOINLINE [1] ifilter #-}++ifilterFB+  :: (a -> t -> t) -> (Int -> a -> Bool) -> a -> (Int# -> t) -> Int# -> t+ifilterFB c p = \x r k ->+  if p (I# k) x then x `c` r (k +# 1#) else r (k +# 1#)+{-# INLINE [0] ifilterFB #-}++{-# RULES+"ifilter"       [~1] forall p xs.    ifilter p xs = build (\c n -> foldr (ifilterFB c p) (\_ -> n) xs 0#)+"ifilterList"   [1]  forall p xs.    foldr (ifilterFB (:) p) (\_ -> []) xs 0# = ifilter p xs+  #-}++itakeWhile :: (Int -> a -> Bool) -> [a] -> [a]+itakeWhile p ls = go 0# ls+  where+    go i (x:xs) | p (I# i) x = x : go (i +# 1#) xs+                | otherwise  = []+    go _ _ = []+{-# NOINLINE [1] itakeWhile #-}++itakeWhileFB+  :: (a -> t -> t) -> (Int -> a -> Bool) -> t -> a -> (Int# -> t) -> Int# -> t+itakeWhileFB c p n = \x r k ->+  if p (I# k) x then x `c` r (k +# 1#) else n+{-# INLINE [0] itakeWhileFB #-}++{-# RULES+"itakeWhile"       [~1] forall p xs.    itakeWhile p xs = build (\c n -> foldr (itakeWhileFB c p n) (\_ -> n) xs 0#)+"itakeWhileList"   [1]  forall p xs.    foldr (itakeWhileFB (:) p []) (\_ -> []) xs 0# = itakeWhile p xs+  #-}++idropWhile :: (Int -> a -> Bool) -> [a] -> [a]+idropWhile p ls = go 0# ls+  where+    go i (x:xs) | p (I# i) x = go (i +# 1#) xs+                | otherwise  = x:xs+    go _ [] = []+{-# INLINE idropWhile #-}++ipartition :: (Int -> a -> Bool) -> [a] -> ([a],[a])+ipartition p xs = ifoldr (iselect p) ([],[]) xs+{-# INLINE ipartition #-}++iselect :: (Int -> a -> Bool) -> Int -> a -> ([a], [a]) -> ([a], [a])+iselect p i x ~(ts,fs) | p i x     = (x:ts,fs)+                       | otherwise = (ts, x:fs)++ifind :: (Int -> a -> Bool) -> [a] -> Maybe (Int, a)+ifind p ls = go 0# ls+  where+    go i (x:xs) | p (I# i) x = Just (I# i, x)+                | otherwise  = go (i +# 1#) xs+    go _ _ = Nothing+{-# INLINE ifind #-}++ifindIndex :: (Int -> a -> Bool) -> [a] -> Maybe Int+ifindIndex p = listToMaybe . ifindIndices p++ifindIndices :: (Int -> a -> Bool) -> [a] -> [Int]+ifindIndices p ls = go 0# ls+  where+    go _ [] = []+    go i (x:xs) | p (I# i) x = I# i : go (i +# 1#) xs+                | otherwise  = go (i +# 1#) xs+{-# NOINLINE [1] ifindIndices #-}++ifindIndicesFB+  :: (Int -> t -> t) -> (Int -> a -> Bool) -> a -> (Int# -> t) -> Int# -> t+ifindIndicesFB c p = \x r k ->+  if p (I# k) x then I# k `c` r (k +# 1#) else r (k +# 1#)+{-# INLINE [0] ifindIndicesFB #-}++{-# RULES+"ifindIndices"       [~1] forall p xs.    ifindIndices p xs = build (\c n -> foldr (ifindIndicesFB c p) (\_ -> n) xs 0#)+"ifindIndicesList"   [1]  forall p xs.    foldr (ifindIndicesFB (:) p) (\_ -> []) xs 0# = ifindIndices p xs+  #-}++{-++errorEmptyList :: String -> a+errorEmptyList fun = error ("Data.List.Index." ++ fun ++ ": empty list")++-}++{- |+/Subject to fusion in the first argument./+-}+izipWith :: (Int -> a -> b -> c) -> [a] -> [b] -> [c]+izipWith fun xs ys = go 0# xs ys+  where+    go i (a:as) (b:bs) = fun (I# i) a b : go (i +# 1#) as bs+    go _ _ _           = []+{-# NOINLINE [1] izipWith #-}++izipWithFB+  :: (c -> t -> t) -> (Int -> a -> b -> c) -> a -> b -> (Int# -> t) -> Int# -> t+izipWithFB c fun = \x y cont i -> fun (I# i) x y `c` cont (i +# 1#)+{-# INLINE [0] izipWithFB #-}++{-# RULES+"izipWith"       [~1] forall f xs ys.    izipWith f xs ys = build (\c n -> foldr2 (izipWithFB c f) (\_ -> n) xs ys 0#)+"izipWithList"   [1]  forall f xs ys.    foldr2 (izipWithFB (:) f) (\_ -> []) xs ys 0# = izipWith f xs ys+  #-}++-- Copied from GHC.List++foldr2 :: (a -> b -> c -> c) -> c -> [a] -> [b] -> c+foldr2 k z = go+  where+        go []    _ys     = z+        go _xs   []      = z+        go (x:xs) (y:ys) = k x y (go xs ys)+{-# INLINE [0] foldr2 #-}++foldr2_left :: (a -> b -> c -> d) -> d -> a -> ([b] -> c) -> [b] -> d+foldr2_left _k  z _x _r []     = z+foldr2_left  k _z  x  r (y:ys) = k x y (r ys)++{-# RULES+"foldr2/left"   forall k z ys (g::forall b.(a->b->b)->b->b) .+                  foldr2 k z (build g) ys = g (foldr2_left  k z) (\_ -> z) ys+ #-}++izipWith3+  :: (Int -> a -> b -> c -> d)+  -> [a] -> [b] -> [c] -> [d]+izipWith3 fun = go 0#+  where+    go i (a:as) (b:bs) (c:cs) =+      fun (I# i) a b c : go (i +# 1#) as bs cs+    go _ _ _ _ = []+{-# INLINE izipWith3 #-}++izipWith4+  :: (Int -> a -> b -> c -> d -> e)+  -> [a] -> [b] -> [c] -> [d] -> [e]+izipWith4 fun = go 0#+  where+    go i (a:as) (b:bs) (c:cs) (d:ds) =+      fun (I# i) a b c d : go (i +# 1#) as bs cs ds+    go _ _ _ _ _ = []+{-# INLINE izipWith4 #-}++izipWith5+  :: (Int -> a -> b -> c -> d -> e -> f)+  -> [a] -> [b] -> [c] -> [d] -> [e] -> [f]+izipWith5 fun = go 0#+  where+    go i (a:as) (b:bs) (c:cs) (d:ds) (e:es) =+      fun (I# i) a b c d e : go (i +# 1#) as bs cs ds es+    go _ _ _ _ _ _ = []+{-# INLINE izipWith5 #-}++izipWith6+  :: (Int -> a -> b -> c -> d -> e -> f -> g)+  -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g]+izipWith6 fun = go 0#+  where+    go i (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) =+      fun (I# i) a b c d e f : go (i +# 1#) as bs cs ds es fs+    go _ _ _ _ _ _ _ = []+{-# INLINE izipWith6 #-}++izipWith7+  :: (Int -> a -> b -> c -> d -> e -> f -> g -> h)+  -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h]+izipWith7 fun = go 0#+  where+    go i (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs) =+      fun (I# i) a b c d e f g : go (i +# 1#) as bs cs ds es fs gs+    go _ _ _ _ _ _ _ _ = []+{-# INLINE izipWith7 #-}++izipWithM :: Applicative f => (Int -> a -> b -> f c) -> [a] -> [b] -> f [c]+izipWithM f as bs = sequenceA (izipWith f as bs)+{-# INLINE izipWithM #-}++izipWithM_ :: Applicative f => (Int -> a -> b -> f c) -> [a] -> [b] -> f ()+izipWithM_ f as bs = sequenceA_ (izipWith f as bs)+{-# INLINE izipWithM_ #-}