├── .github └── CODEOWNERS ├── .gitignore ├── .stylish-haskell.yaml ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── app └── Main.hs ├── benchmark └── Main.hs ├── containers-backpack.cabal ├── src ├── benchmarks │ └── Map │ │ └── Bench.hs ├── contrib │ └── Map │ │ └── Contrib │ │ └── Group.hs ├── int-strict │ └── Map │ │ └── Int.hs ├── laws │ └── Map │ │ └── Laws.hs ├── ordered-strict │ └── Map │ │ └── Ord.hs ├── primitive │ └── Map │ │ └── Prim.hs ├── sig │ └── Map.hsig └── unordered-strict │ └── Map │ └── Hash.hs └── test └── Main.hs /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @chshersh @vrom911 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ### Haskell 2 | dist 3 | dist-* 4 | cabal-dev 5 | *.o 6 | *.hi 7 | *.chi 8 | *.chs.h 9 | *.dyn_o 10 | *.dyn_hi 11 | *.prof 12 | *.aux 13 | *.hp 14 | *.eventlog 15 | .virtualenv 16 | .hsenv 17 | .hpc 18 | .cabal-sandbox/ 19 | cabal.sandbox.config 20 | cabal.config 21 | cabal.project.local 22 | .ghc.environment.* 23 | .HTF/ 24 | # Stack 25 | .stack-work/ 26 | 27 | ### IDE/support 28 | # Vim 29 | [._]*.s[a-v][a-z] 30 | [._]*.sw[a-p] 31 | [._]s[a-v][a-z] 32 | [._]sw[a-p] 33 | *~ 34 | tags 35 | 36 | # IntellijIDEA 37 | .idea/ 38 | .ideaHaskellLib/ 39 | *.iml 40 | 41 | # Atom 42 | .haskell-ghc-mod.json 43 | 44 | # VS 45 | .vscode/ 46 | 47 | # Emacs 48 | *# 49 | .dir-locals.el 50 | TAGS 51 | 52 | # other 53 | .DS_Store 54 | 55 | -------------------------------------------------------------------------------- /.stylish-haskell.yaml: -------------------------------------------------------------------------------- 1 | steps: 2 | - simple_align: 3 | cases: true 4 | top_level_patterns: true 5 | records: true 6 | 7 | # Import cleanup 8 | - imports: 9 | align: none 10 | list_align: after_alias 11 | pad_module_names: false 12 | long_list_align: inline 13 | empty_list_align: inherit 14 | list_padding: 4 15 | separate_lists: true 16 | space_surround: false 17 | 18 | - language_pragmas: 19 | style: vertical 20 | remove_redundant: true 21 | 22 | # Remove trailing whitespace 23 | - trailing_whitespace: {} 24 | 25 | columns: 100 26 | 27 | newline: native 28 | 29 | language_extensions: 30 | - BangPatterns 31 | - ConstraintKinds 32 | - DataKinds 33 | - DefaultSignatures 34 | - DeriveAnyClass 35 | - DeriveDataTypeable 36 | - DeriveGeneric 37 | - DerivingStrategies 38 | - DerivingVia 39 | - ExplicitNamespaces 40 | - FlexibleContexts 41 | - FlexibleInstances 42 | - FunctionalDependencies 43 | - GADTs 44 | - GeneralizedNewtypeDeriving 45 | - InstanceSigs 46 | - KindSignatures 47 | - LambdaCase 48 | - MultiParamTypeClasses 49 | - MultiWayIf 50 | - NamedFieldPuns 51 | - NoImplicitPrelude 52 | - OverloadedStrings 53 | - QuasiQuotes 54 | - RecordWildCards 55 | - ScopedTypeVariables 56 | - StandaloneDeriving 57 | - TemplateHaskell 58 | - TupleSections 59 | - TypeApplications 60 | - TypeFamilies 61 | - ViewPatterns 62 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: true 2 | language: haskell 3 | 4 | git: 5 | depth: 5 6 | 7 | cabal: "3.0" 8 | 9 | cache: 10 | directories: 11 | - "$HOME/.cabal/store" 12 | - "$HOME/.stack" 13 | - "$TRAVIS_BUILD_DIR/.stack-work" 14 | 15 | matrix: 16 | include: 17 | - ghc: 8.2.2 18 | - ghc: 8.4.4 19 | - ghc: 8.6.5 20 | 21 | install: 22 | - cabal update 23 | - cabal build --enable-tests --enable-benchmarks 24 | 25 | script: 26 | - cabal test --enable-tests 27 | 28 | notifications: 29 | email: false 30 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | `containers-backpack` uses [PVP Versioning][1]. 4 | The changelog is available [on GitHub][2]. 5 | 6 | ## 0.0.0.0 7 | 8 | * Initially created. 9 | 10 | [1]: https://pvp.haskell.org 11 | [2]: https://github.com/kowainik/containers-backpack/releases 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # containers-backpack 2 | 3 | ![backpack 1](https://user-images.githubusercontent.com/4276606/44077109-23f24b62-9fd5-11e8-8069-b6ca9e45db79.png) 4 | [![MPL-2.0 license](https://img.shields.io/badge/license-MPL--2.0-blue.svg)](https://github.com/kowainik/containers-backpack/blob/main/LICENSE) 5 | [![Build status](https://secure.travis-ci.org/kowainik/containers-backpack.svg)](https://travis-ci.org/kowainik/containers-backpack) 6 | 7 | > _You can't just carry everyone else's hopes and fears around in your backpack and expect to stand up straight._ 8 | > 9 | > David Kirk 10 | 11 | See detailed description in the blog post: 12 | 13 | * [Picnic: put containers into a Backpack](https://kowainik.github.io/posts/2018-08-19-picnic-put-containers-into-a-backpack) 14 | 15 | Structure of this repository: 16 | 17 | * `containers-sig-readonly`: signatures for read-only maps 18 | * `containers-sig`: signatures for maps that can be modified 19 | * `containers-ordered-strict`: implementation of signatures for the [`Map.Strict`](https://hackage.haskell.org/package/containers-0.6.0.1/docs/Data-Map-Strict.html) data type from the [`containers`](https://hackage.haskell.org/package/containers) package 20 | * `containers-int-strict`: implementation of signatures for the [`IntMap.Strict`](https://hackage.haskell.org/package/containers-0.6.0.1/docs/Data-IntMap-Strict.html) type from the [`containers`](https://hackage.haskell.org/package/containers) package 21 | * `containers-unordered-strict`: implementation of signatures for the [`HashMap.Strict`](http://hackage.haskell.org/package/unordered-containers-0.2.9.0/docs/Data-HashMap-Strict.html) from the [`unordered-containers`](http://hackage.haskell.org/package/unordered-containers) package 22 | * `containers-primitive`: implementation of signatures for the [`Map.Lifted.Lifted`](http://hackage.haskell.org/package/primitive-containers-0.2.0/docs/Data-Map-Lifted-Lifted.html) from the [`primitive-containers`](http://hackage.haskell.org/package/primitive-containers) package 23 | * `containers-contrib-readonly`: general functions for maps implemented using the `containers-sig-readonly` package 24 | * `containers-contrib`: general functions for maps implemented using the `containers-sig-readonly` and `containers-sig` packages 25 | * `containers-example`: package that mixes signatures and different implementations 26 | 27 | 28 | ### Acknowledgement 29 | 30 | Icons made by [Freepik](http://www.freepik.com) from [www.flaticon.com](https://www.flaticon.com/) is licensed by [CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/). 31 | -------------------------------------------------------------------------------- /app/Main.hs: -------------------------------------------------------------------------------- 1 | module Main (main) where 2 | 3 | import qualified Map.Contrib.Group.Hash as HM (groupBy) 4 | import qualified Map.Contrib.Group.Int as IM (groupBy) 5 | import qualified Map.Contrib.Group.Ord as M (groupBy) 6 | 7 | 8 | main :: IO () 9 | main = do 10 | putStrLn "### IntMap ###" 11 | print $ IM.groupBy (`mod` 2) [1..10] 12 | 13 | putStrLn "### Map ###" 14 | print $ M.groupBy (`mod` 2) ([1..10] :: [Int]) 15 | 16 | putStrLn "### HashMap ###" 17 | print $ HM.groupBy (`mod` 2) ([1..10] :: [Int]) 18 | -------------------------------------------------------------------------------- /benchmark/Main.hs: -------------------------------------------------------------------------------- 1 | module Main (main) where 2 | 3 | import Gauge.Main (defaultMain) 4 | 5 | import qualified Map.Bench.Hash as Hash 6 | import qualified Map.Bench.Int as Int 7 | import qualified Map.Bench.Ord as Ord 8 | 9 | 10 | main :: IO () 11 | main = do 12 | let lookupRangeLower :: Int 13 | lookupRangeLower = 0 14 | let lookupRangeUpper :: Int 15 | lookupRangeUpper = 1024 16 | 17 | -- Apply bounds to the given benchmark function 18 | let applyBounds :: ((Int, Int) -> a) -> a 19 | applyBounds f = f (lookupRangeLower, lookupRangeUpper) 20 | 21 | defaultMain =<< sequence 22 | [ applyBounds Int.simpleBenchmark "intmap" 23 | , applyBounds Ord.simpleBenchmark "ordmap" 24 | , applyBounds Hash.simpleBenchmark "hashmap" 25 | ] 26 | -------------------------------------------------------------------------------- /containers-backpack.cabal: -------------------------------------------------------------------------------- 1 | cabal-version: 3.0 2 | name: containers-backpack 3 | version: 0.0.0.0 4 | synopsis: Backpack signatures for Map-like interfaces 5 | description: Backpack signatures for Map-like interfaces 6 | homepage: https://github.com/kowainik/containers-backpack 7 | bug-reports: https://github.com/kowainik/containers-backpack/issues 8 | license: MPL-2.0 9 | license-file: LICENSE 10 | author: Dmitrii Kovanikov, Veronika Romashkina 11 | maintainer: Kowainik 12 | copyright: 2018-2019 Kowainik 13 | category: Backpack, Data, Containers 14 | build-type: Simple 15 | extra-doc-files: CHANGELOG.md 16 | README.md 17 | tested-with: GHC == 8.2.2 18 | GHC == 8.4.4 19 | GHC == 8.6.5 20 | 21 | source-repository head 22 | type: git 23 | location: https://github.com/kowainik/containers-backpack.git 24 | 25 | common common-options 26 | build-depends: base >= 4.10.1.0 && < 4.13 27 | 28 | ghc-options: -Wall 29 | -Wincomplete-uni-patterns 30 | -Wincomplete-record-updates 31 | -Wcompat 32 | -Widentities 33 | -Wredundant-constraints 34 | -Wmissing-export-lists 35 | -Wpartial-fields 36 | -fhide-source-paths 37 | if impl(ghc >= 8.8.1) 38 | ghc-options: -Wmissing-deriving-strategies 39 | -Werror=missing-deriving-strategies 40 | 41 | default-language: Haskell2010 42 | default-extensions: ConstraintKinds 43 | DeriveGeneric 44 | DerivingStrategies 45 | InstanceSigs 46 | GeneralizedNewtypeDeriving 47 | LambdaCase 48 | OverloadedStrings 49 | RecordWildCards 50 | ScopedTypeVariables 51 | StandaloneDeriving 52 | TupleSections 53 | TypeApplications 54 | ViewPatterns 55 | 56 | -- signatures for containers 57 | library sig 58 | import: common-options 59 | visibility: public 60 | hs-source-dirs: src/sig 61 | signatures: Map 62 | 63 | -- signature implementation for containers.Map.Strict 64 | library ordered-strict 65 | import: common-options 66 | visibility: public 67 | hs-source-dirs: src/ordered-strict 68 | exposed-modules: Map.Ord 69 | reexported-modules: Map.Ord as Map 70 | build-depends: containers >= 0.5.10.1 && < 0.7 71 | ghc-options: -fexpose-all-unfoldings 72 | 73 | -- signature implementation for containers.IntMap.Strict 74 | library int-strict 75 | import: common-options 76 | visibility: public 77 | hs-source-dirs: src/int-strict 78 | exposed-modules: Map.Int 79 | reexported-modules: Map.Int as Map 80 | build-depends: containers >= 0.5.10.1 && < 0.7 81 | , deepseq ^>= 1.4 82 | ghc-options: -fexpose-all-unfoldings 83 | 84 | -- signature implementation for unordered-containers.HashMap.Strict 85 | library unordered-strict 86 | import: common-options 87 | visibility: public 88 | hs-source-dirs: src/unordered-strict 89 | exposed-modules: Map.Hash 90 | reexported-modules: Map.Hash as Map 91 | build-depends: hashable >= 1.2.7.0 && < 1.4 92 | , unordered-containers ^>= 0.2.7.0 93 | ghc-options: -fexpose-all-unfoldings 94 | 95 | -- TODO: support for primitive containers temporary disabled 96 | -- -- signature implementation for primitive-containers.Map.Lifted 97 | -- library primitive 98 | -- import: common-options 99 | -- visibility: public 100 | -- hs-source-dirs: src/primitive 101 | -- exposed-modules: Map.Prim 102 | -- reexported-modules: Map.Prim as Map 103 | -- build-depends: primitive-containers ^>= 0.4.0 104 | -- ghc-options: -fexpose-all-unfoldings 105 | 106 | -- implementations of various general functions via signatures 107 | library contrib 108 | import: common-options 109 | visibility: public 110 | hs-source-dirs: src/contrib 111 | exposed-modules: Map.Contrib.Group 112 | build-depends: containers-backpack:sig 113 | 114 | -- property laws tests for readonly containers via signatures 115 | library laws 116 | import: common-options 117 | visibility: public 118 | hs-source-dirs: src/laws 119 | exposed-modules: Map.Laws 120 | build-depends: containers-backpack:sig, QuickCheck ^>= 2.13 121 | 122 | -- benchmarks in terms of signatures 123 | library benchmarks 124 | import: common-options 125 | visibility: public 126 | hs-source-dirs: src/benchmarks 127 | exposed-modules: Map.Bench 128 | build-depends: containers-backpack:sig, gauge ^>= 0.2.5, relude ^>= 0.5.0 129 | -- TODO: ^ write in several lines when parsing of several lines with MPL is supported 130 | -- * https://github.com/haskell/cabal/issues/5846 131 | 132 | executable example 133 | import: common-options 134 | hs-source-dirs: app 135 | main-is: Main.hs 136 | build-depends: contrib 137 | , int-strict 138 | , ordered-strict 139 | , unordered-strict 140 | 141 | -- NOTE: need to omit prefix due to bug 142 | -- * https://github.com/haskell/cabal/issues/6281 143 | mixins: contrib (Map.Contrib.Group as Map.Contrib.Group.Int) 144 | requires (Map as Map.Int) 145 | , contrib (Map.Contrib.Group as Map.Contrib.Group.Ord) 146 | requires (Map as Map.Ord) 147 | , contrib (Map.Contrib.Group as Map.Contrib.Group.Hash) 148 | requires (Map as Map.Hash) 149 | 150 | test-suite laws-test 151 | import: common-options 152 | type: exitcode-stdio-1.0 153 | hs-source-dirs: test 154 | main-is: Main.hs 155 | build-depends: hashable >= 1.2.7.0 && < 1.4 156 | , text 157 | , QuickCheck 158 | -- containers-backpack libraries 159 | , laws 160 | , int-strict 161 | , ordered-strict 162 | , unordered-strict 163 | 164 | mixins: laws (Map.Laws as Map.Laws.Int) 165 | requires (Map as Map.Int) 166 | , laws (Map.Laws as Map.Laws.Ord) 167 | requires (Map as Map.Ord) 168 | , laws (Map.Laws as Map.Laws.Hash) 169 | requires (Map as Map.Hash) 170 | 171 | ghc-options: -threaded 172 | -rtsopts 173 | -with-rtsopts=-N 174 | 175 | benchmark simple-benchmark 176 | import: common-options 177 | type: exitcode-stdio-1.0 178 | hs-source-dirs: benchmark 179 | main-is: Main.hs 180 | 181 | build-depends: gauge ^>= 0.2.5 182 | -- containers-backpack libraries 183 | , benchmarks 184 | , int-strict 185 | , ordered-strict 186 | , unordered-strict 187 | 188 | mixins: benchmarks (Map.Bench as Map.Bench.Int) 189 | requires (Map as Map.Int) 190 | , benchmarks (Map.Bench as Map.Bench.Ord) 191 | requires (Map as Map.Ord) 192 | , benchmarks (Map.Bench as Map.Bench.Hash) 193 | requires (Map as Map.Hash) 194 | 195 | ghc-options: -threaded 196 | -rtsopts 197 | -with-rtsopts=-N 198 | -------------------------------------------------------------------------------- /src/benchmarks/Map/Bench.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE AllowAmbiguousTypes #-} 2 | {-# LANGUAGE FlexibleContexts #-} 3 | {-# LANGUAGE NoImplicitPrelude #-} 4 | {-# LANGUAGE TypeFamilies #-} 5 | 6 | module Map.Bench 7 | ( simpleBenchmark 8 | ) where 9 | 10 | import Relude hiding (Map, fromList) 11 | 12 | import Gauge.Main (Benchmark, bench, bgroup, whnf) 13 | 14 | import Map (Key, Map, fromList, lookup) 15 | 16 | 17 | simpleBenchmark 18 | :: forall k . 19 | (Enum k, Key k, NFData (Map k Int)) 20 | => (k, k) 21 | -> String 22 | -> IO Benchmark 23 | simpleBenchmark (lower, upper) structureName = do 24 | let map_keys :: [k] = [lower..upper] 25 | 26 | let mapEntries = zip map_keys [0..] 27 | 28 | let m = fromList mapEntries 29 | 30 | evaluateNF_ m 31 | 32 | pure $ bgroup structureName 33 | [ lookupBench ("lookup/all") m (map fst mapEntries) 34 | ] 35 | 36 | lookupBench :: forall k. Key k => String -> Map k Int -> [k] -> Benchmark 37 | lookupBench structureName m = bench structureName . whnf (go 0) 38 | where 39 | go :: Int -> [k] -> Int 40 | go = foldl' (\a -> (a +) . fromMaybe 0 . flip lookup m) 41 | -------------------------------------------------------------------------------- /src/contrib/Map/Contrib/Group.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE MonoLocalBinds #-} 2 | {-# LANGUAGE TypeFamilies #-} 3 | 4 | module Map.Contrib.Group 5 | ( groupBy 6 | , groupOneBy 7 | ) where 8 | 9 | import Data.Foldable (foldl') 10 | import Data.List.NonEmpty (NonEmpty (..), (<|)) 11 | import Prelude hiding (lookup) 12 | 13 | import Map (Key, Map, alter, empty) 14 | 15 | 16 | {- | Groups elements using results of the given function as keys. 17 | 18 | >>> groupBy even [1..6] 19 | fromList [(False,5 :| [3,1]),(True,6 :| [4,2])] 20 | -} 21 | groupBy 22 | :: forall f k a . (Foldable f, Key k) 23 | => (a -> k) 24 | -> f a 25 | -> Map k (NonEmpty a) 26 | groupBy f = foldl' mapGroup empty 27 | where 28 | mapGroup :: Map k (NonEmpty a) -> a -> Map k (NonEmpty a) 29 | mapGroup m a = 30 | let toVal :: Maybe (NonEmpty a) -> NonEmpty a 31 | toVal Nothing = a :| [] 32 | toVal (Just xs) = a <| xs 33 | in alter (Just . toVal) (f a) m 34 | 35 | {- | Similar to 'groupBy' but keeps only one element as value. 36 | 37 | >>> groupOneBy even [1 .. 6] 38 | fromList [(False,1),(True,2)] 39 | -} 40 | groupOneBy 41 | :: forall f k a . (Foldable f, Key k) 42 | => (a -> k) 43 | -> f a 44 | -> Map k a 45 | groupOneBy f = foldl' mapGroup empty 46 | where 47 | mapGroup :: Map k a -> a -> Map k a 48 | mapGroup m a = 49 | let toVal :: Maybe a -> a 50 | toVal Nothing = a 51 | toVal (Just x) = x 52 | in alter (Just . toVal) (f a) m 53 | -------------------------------------------------------------------------------- /src/int-strict/Map/Int.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE FlexibleInstances #-} 2 | {-# LANGUAGE TypeFamilies #-} 3 | 4 | module Map.Int 5 | ( Map 6 | , Key 7 | 8 | , empty 9 | , singleton 10 | , fromList 11 | 12 | , null 13 | , size 14 | , member 15 | , lookup 16 | , lookupDefault 17 | 18 | , toList 19 | , keys 20 | , elems 21 | 22 | , insert 23 | , insertWith 24 | , adjust 25 | , update 26 | , delete 27 | , alter 28 | ) where 29 | 30 | import Control.DeepSeq (NFData (..)) 31 | import Data.Coerce (coerce) 32 | import Prelude hiding (lookup, null) 33 | 34 | import qualified Data.IntMap.Strict as M 35 | 36 | 37 | newtype Map k v = IM (M.IntMap v) 38 | deriving newtype (Show, Eq, NFData) 39 | 40 | type Key = (~) Int 41 | 42 | empty :: forall k v. Map k v 43 | empty = coerce @(M.IntMap v) M.empty 44 | {-# INLINE empty #-} 45 | 46 | singleton :: forall k v. Key k => k -> v -> Map k v 47 | singleton = coerce @(k -> v -> M.IntMap v) M.singleton 48 | {-# INLINE singleton #-} 49 | 50 | fromList :: forall k v. Key k => [(k, v)] -> Map k v 51 | fromList = coerce @([(k, v)] -> M.IntMap v) M.fromList 52 | {-# INLINE fromList #-} 53 | 54 | null :: forall k v. Map k v -> Bool 55 | null = coerce @(M.IntMap v -> Bool) M.null 56 | {-# INLINE null #-} 57 | 58 | size :: forall k v. Map k v -> Int 59 | size = coerce @(M.IntMap v -> Int) M.size 60 | {-# INLINE size #-} 61 | 62 | member :: forall k v. Key k => k -> Map k v -> Bool 63 | member = coerce @(k -> M.IntMap v -> Bool) M.member 64 | {-# INLINE member #-} 65 | 66 | lookup :: forall k v. Key k => k -> Map k v -> Maybe v 67 | lookup = coerce @(k -> M.IntMap v -> Maybe v) M.lookup 68 | {-# INLINE lookup #-} 69 | 70 | lookupDefault :: forall k v. Key k => v -> k -> Map k v -> v 71 | lookupDefault = coerce @(v -> k -> M.IntMap v -> v) M.findWithDefault 72 | {-# INLINE lookupDefault #-} 73 | 74 | toList :: forall k v. Key k => Map k v -> [(k, v)] 75 | toList = coerce @(M.IntMap v -> [(k, v)]) M.toList 76 | {-# INLINE toList #-} 77 | 78 | keys :: forall k v. Key k => Map k v -> [k] 79 | keys = coerce @(M.IntMap v -> [k]) M.keys 80 | {-# INLINE keys #-} 81 | 82 | elems :: forall k v. Map k v -> [v] 83 | elems = coerce @(M.IntMap v -> [v]) M.elems 84 | {-# INLINE elems #-} 85 | 86 | insert :: forall k v. Key k => k -> v -> Map k v -> Map k v 87 | insert = coerce @(k -> v -> M.IntMap v -> M.IntMap v) M.insert 88 | {-# INLINE insert #-} 89 | 90 | insertWith :: forall k v. Key k => (v -> v -> v) -> k -> v -> Map k v -> Map k v 91 | insertWith = coerce @((v -> v -> v) -> k -> v -> M.IntMap v -> M.IntMap v) M.insertWith 92 | {-# INLINE insertWith #-} 93 | 94 | adjust :: forall k v. Key k => (v -> v) -> k -> Map k v -> Map k v 95 | adjust = coerce @((v -> v) -> k -> M.IntMap v -> M.IntMap v) M.adjust 96 | {-# INLINE adjust #-} 97 | 98 | update :: forall k v. Key k => (v -> Maybe v) -> k -> Map k v -> Map k v 99 | update = coerce @((v -> Maybe v) -> k -> M.IntMap v -> M.IntMap v) M.update 100 | {-# INLINE update #-} 101 | 102 | delete :: forall k v. Key k => k -> Map k v -> Map k v 103 | delete = coerce @(k -> M.IntMap v -> M.IntMap v) M.delete 104 | {-# INLINE delete #-} 105 | 106 | alter :: forall k v. Key k => (Maybe v -> Maybe v) -> k -> Map k v -> Map k v 107 | alter = coerce @((Maybe v -> Maybe v) -> k -> M.IntMap v -> M.IntMap v) M.alter 108 | {-# INLINE alter #-} 109 | -------------------------------------------------------------------------------- /src/laws/Map/Laws.hs: -------------------------------------------------------------------------------- 1 | {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} 2 | 3 | {-# LANGUAGE RankNTypes #-} 4 | {-# LANGUAGE TypeFamilies #-} 5 | 6 | module Map.Laws 7 | ( checkLaws 8 | 9 | -- * Exported for containers-example module. It demonstrates the law execution. 10 | , singletonFromList 11 | ) where 12 | 13 | import Control.Monad (replicateM) 14 | import Data.Proxy (Proxy) 15 | import Map (Key, alter, delete, elems, empty, fromList, insert, keys, lookup, lookupDefault, member, 16 | null, singleton, size, toList, update) 17 | import Prelude hiding (lookup, null) 18 | import Test.QuickCheck (Arbitrary, Gen, Property, arbitrary, choose, quickCheck, (==>)) 19 | 20 | 21 | nullEmpty :: Bool 22 | nullEmpty = null empty 23 | 24 | nullImpliesZeroSize :: Key k => Gen [(k, v)] -> Gen Property 25 | nullImpliesZeroSize pairs = do 26 | m <- fromList <$> pairs 27 | pure $ null m ==> size m == 0 28 | 29 | nonZeroSizeImpliesNotNull :: Key k => [(k, v)] -> Property 30 | nonZeroSizeImpliesNotNull (fromList -> m) = size m > 0 ==> not (null m) 31 | 32 | emptyZeroSized :: Bool 33 | emptyZeroSized = size empty == 0 34 | 35 | sizeIsNatural :: Key k => [(k, v)] -> Bool 36 | sizeIsNatural (fromList -> m) = size m >= 0 37 | 38 | singletonOneSized :: Key k => k -> v -> Bool 39 | singletonOneSized k v = size (singleton k v) == 1 40 | 41 | memberEmptyFalse :: Key k => k -> Bool 42 | memberEmptyFalse k = not $ member k empty 43 | 44 | memberSingletonSame :: Key k => k -> v -> Bool 45 | memberSingletonSame k v = member k $ singleton k v 46 | 47 | newMemberYieldsValidValue :: (Key k, Eq v) => k -> v -> Bool 48 | newMemberYieldsValidValue k v = lookup k (singleton k v) == Just v 49 | 50 | lookupDefaultEmpty :: (Key k, Eq v) => k -> v -> Bool 51 | lookupDefaultEmpty k v = lookupDefault v k empty == v 52 | 53 | listToSingleton :: (Key k, Eq k, Eq v) => k -> v -> Bool 54 | listToSingleton k v = toList (singleton k v) == [(k, v)] 55 | 56 | singletonFromList :: (Key k, Eq k, Eq v) => k -> v -> Bool 57 | singletonFromList k v = singleton k v == fromList [(k, v)] 58 | 59 | keysOfSingleton :: (Key k, Eq k, Eq v) => k -> v -> Bool 60 | keysOfSingleton k v = keys (singleton k v) == [k] 61 | 62 | elemsOfSingleton :: (Key k, Eq k, Eq v) => k -> v -> Bool 63 | elemsOfSingleton k v = elems (singleton k v) == [v] 64 | 65 | lookupMatchMember :: Key k => k -> [(k, v)] -> Bool 66 | lookupMatchMember k (fromList -> m) = match (lookup k m) (member k m) 67 | where 68 | match :: Maybe v -> Bool -> Bool 69 | match Nothing False = True 70 | match Nothing True = False 71 | match (Just _) False = False 72 | match (Just _) True = True 73 | 74 | emptyInsertSingleton :: (Key k, Eq k, Eq v) => k -> v -> Bool 75 | emptyInsertSingleton k v = singleton k v == insert k v empty 76 | 77 | insertDeleteEmpty :: (Key k, Eq k, Eq v) => k -> v -> Bool 78 | insertDeleteEmpty k v = delete k (insert k v empty) == empty 79 | 80 | updateNothingRemoves :: (Key k, Eq k, Eq v) => k -> v -> Bool 81 | updateNothingRemoves k v = update (const Nothing) k (singleton k v) == empty 82 | 83 | updateJustId :: (Key k, Eq k, Eq v) => k -> [(k, v)] -> Bool 84 | updateJustId k pairs = update Just k m == m where m = fromList pairs 85 | 86 | alterCanInsert :: (Key k, Eq k, Eq v) => k -> v -> Bool 87 | alterCanInsert k v = alter (const (Just v)) k empty == singleton k v 88 | 89 | genSmallPairs :: (Key l, Arbitrary l, Arbitrary r) => Gen [(l, r)] 90 | genSmallPairs = do 91 | len <- choose (0, 2) 92 | replicateM len $ (,) <$> arbitrary <*> arbitrary 93 | 94 | checkLaws 95 | :: forall k v. (Key k, Arbitrary k, Arbitrary v, Show k, Show v, Eq k, Eq v) 96 | => Proxy k 97 | -> Proxy v 98 | -> IO () 99 | checkLaws _ _ = do 100 | -- query properties 101 | quickCheck nullEmpty 102 | quickCheck $ nullImpliesZeroSize (genSmallPairs @k @v) 103 | quickCheck $ nonZeroSizeImpliesNotNull @k @v 104 | quickCheck emptyZeroSized 105 | quickCheck $ sizeIsNatural @k @v 106 | quickCheck $ singletonOneSized @k @v 107 | quickCheck $ memberEmptyFalse @k 108 | quickCheck $ memberSingletonSame @k @v 109 | quickCheck $ newMemberYieldsValidValue @k @v 110 | quickCheck $ lookupDefaultEmpty @k @v 111 | quickCheck $ listToSingleton @k @v 112 | quickCheck $ singletonFromList @k @v 113 | quickCheck $ keysOfSingleton @k @v 114 | quickCheck $ elemsOfSingleton @k @v 115 | quickCheck $ lookupMatchMember @k @v 116 | 117 | -- update properties 118 | quickCheck $ emptyInsertSingleton @k @v 119 | quickCheck $ insertDeleteEmpty @k @v 120 | quickCheck $ updateNothingRemoves @k @v 121 | quickCheck $ updateJustId @k @v 122 | quickCheck $ alterCanInsert @k @v 123 | -------------------------------------------------------------------------------- /src/ordered-strict/Map/Ord.hs: -------------------------------------------------------------------------------- 1 | {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} 2 | 3 | module Map.Ord 4 | ( Map 5 | , Key 6 | 7 | , M.empty 8 | , singleton 9 | , M.fromList 10 | 11 | , M.null 12 | , M.size 13 | , M.member 14 | , M.lookup 15 | , lookupDefault 16 | 17 | , toList 18 | , keys 19 | , M.elems 20 | 21 | , M.insert 22 | , M.insertWith 23 | , M.adjust 24 | , M.update 25 | , M.delete 26 | , M.alter 27 | ) where 28 | 29 | import Prelude hiding (lookup, null) 30 | 31 | import qualified Data.Map.Strict as M 32 | 33 | 34 | type Map = M.Map 35 | type Key = Ord 36 | 37 | lookupDefault :: Key k => v -> k -> Map k v -> v 38 | lookupDefault = M.findWithDefault 39 | {-# INLINE lookupDefault #-} 40 | 41 | toList :: Key k => Map k v -> [(k, v)] 42 | toList = M.toList 43 | {-# INLINE toList #-} 44 | 45 | keys :: Key k => Map k v -> [k] 46 | keys = M.keys 47 | {-# INLINE keys #-} 48 | 49 | singleton :: Key k => k -> v -> Map k v 50 | singleton = M.singleton 51 | {-# INLINE singleton #-} 52 | -------------------------------------------------------------------------------- /src/primitive/Map/Prim.hs: -------------------------------------------------------------------------------- 1 | {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} 2 | 3 | module Map.Prim 4 | ( Map 5 | , Key 6 | 7 | , M.empty 8 | , singleton 9 | , M.fromList 10 | 11 | , null 12 | , M.size 13 | , member 14 | , M.lookup 15 | , lookupDefault 16 | 17 | , toList 18 | , keys 19 | , elems 20 | ) where 21 | 22 | import Data.Maybe (fromMaybe, isJust) 23 | import Prelude hiding (lookup, null) 24 | 25 | import qualified Data.Map.Lifted.Lifted as M 26 | import qualified GHC.Exts as L 27 | 28 | 29 | type Map = M.Map 30 | type Key = Ord 31 | 32 | singleton :: Key k => k -> v -> Map k v 33 | singleton = M.singleton 34 | {-# INLINE singleton #-} 35 | 36 | null :: Map k v -> Bool 37 | null = (== 0) . M.size 38 | {-# INLINE null #-} 39 | 40 | member :: Key k => k -> Map k a -> Bool 41 | member k = isJust . M.lookup k 42 | {-# INLINE member #-} 43 | 44 | lookupDefault :: Key k => v -> k -> Map k v -> v 45 | lookupDefault def k = fromMaybe def . M.lookup k 46 | {-# INLINE lookupDefault #-} 47 | 48 | toList :: Key k => Map k v -> [(k, v)] 49 | toList = L.toList 50 | {-# INLINE toList #-} 51 | 52 | keys :: Key k => Map k v -> [k] 53 | keys = map fst . toList 54 | {-# INLINE keys #-} 55 | 56 | elems :: Map k v -> [v] 57 | elems = M.foldrWithKey' cons [] 58 | where 59 | cons :: k -> v -> [v] -> [v] 60 | cons _ = (:) 61 | {-# INLINE elems #-} 62 | -------------------------------------------------------------------------------- /src/sig/Map.hsig: -------------------------------------------------------------------------------- 1 | signature Map 2 | ( -- * Types 3 | Map 4 | , Key 5 | 6 | -- * Construction 7 | , empty 8 | , singleton 9 | , fromList 10 | 11 | -- * Query 12 | , null 13 | , size 14 | , member 15 | , lookup 16 | , lookupDefault 17 | 18 | -- * Conversion 19 | , toList 20 | , keys 21 | , elems 22 | 23 | -- * Update 24 | , insert 25 | , insertWith 26 | , adjust 27 | , update 28 | , delete 29 | , alter 30 | ) where 31 | 32 | import Prelude hiding (lookup, null) 33 | 34 | 35 | data Map k v 36 | class Key k 37 | 38 | instance (Show k, Show v) => Show (Map k v) 39 | instance ( Eq k, Eq v) => Eq (Map k v) 40 | 41 | -- TODO: construction from corresponding sets 42 | empty :: Map k v 43 | singleton :: Key k => k -> v -> Map k v 44 | fromList :: Key k => [(k, v)] -> Map k v 45 | 46 | null :: Map k v -> Bool 47 | size :: Map k v -> Int 48 | member :: Key k => k -> Map k a -> Bool 49 | lookup :: Key k => k -> Map k v -> Maybe v 50 | lookupDefault :: Key k => v -> k -> Map k v -> v 51 | 52 | insert :: Key k => k -> v -> Map k v -> Map k v 53 | insertWith :: Key k => (v -> v -> v) -> k -> v -> Map k v -> Map k v 54 | adjust :: Key k => (a -> a) -> k -> Map k a -> Map k a 55 | update :: Key k => (a -> Maybe a) -> k -> Map k a -> Map k a 56 | delete :: Key k => k -> Map k v -> Map k v 57 | alter :: Key k => (Maybe v -> Maybe v) -> k -> Map k v -> Map k v 58 | 59 | -- TODO: these two functions require constraints 60 | toList :: Key k => Map k v -> [(k, v)] 61 | keys :: Key k => Map k v -> [k] 62 | elems :: Map k v -> [v] 63 | 64 | -- TODO: union, difference, intersection 65 | -- TODO: folds and traversals 66 | -- TODO: filters, map 67 | 68 | -- infixl 9 !? 69 | -- (!?) :: Key k => Map k v -> k -> Maybe v 70 | -- (!?) m k = lookup k m 71 | -------------------------------------------------------------------------------- /src/unordered-strict/Map/Hash.hs: -------------------------------------------------------------------------------- 1 | {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} 2 | 3 | {-# LANGUAGE FlexibleInstances #-} 4 | {-# LANGUAGE MonoLocalBinds #-} 5 | {-# LANGUAGE UndecidableInstances #-} 6 | 7 | module Map.Hash 8 | ( Map 9 | , Key 10 | 11 | , empty 12 | , singleton 13 | , fromList 14 | 15 | , null 16 | , size 17 | , member 18 | , lookup 19 | , lookupDefault 20 | 21 | , toList 22 | , keys 23 | , elems 24 | 25 | , insert 26 | , insertWith 27 | , adjust 28 | , update 29 | , delete 30 | , alter 31 | ) where 32 | 33 | import Data.Hashable (Hashable) 34 | import Prelude hiding (lookup, null) 35 | 36 | import qualified Data.HashMap.Strict as HM 37 | 38 | 39 | type Map = HM.HashMap 40 | 41 | class (Eq k, Hashable k) => Key k 42 | instance (Eq k, Hashable k) => Key k 43 | 44 | empty :: Map k v 45 | empty = HM.empty 46 | {-# INLINE empty #-} 47 | 48 | singleton :: Key k => k -> v -> Map k v 49 | singleton = HM.singleton 50 | {-# INLINE singleton #-} 51 | 52 | fromList :: Key k => [(k, v)] -> Map k v 53 | fromList = HM.fromList 54 | {-# INLINE fromList #-} 55 | 56 | null :: Map k v -> Bool 57 | null = HM.null 58 | {-# INLINE null #-} 59 | 60 | size :: Map k v -> Int 61 | size = HM.size 62 | {-# INLINE size #-} 63 | 64 | member :: Key k => k -> Map k a -> Bool 65 | member = HM.member 66 | {-# INLINE member #-} 67 | 68 | lookup :: Key k => k -> Map k v -> Maybe v 69 | lookup = HM.lookup 70 | {-# INLINE lookup #-} 71 | 72 | lookupDefault :: Key k => v -> k -> Map k v -> v 73 | lookupDefault = HM.lookupDefault 74 | {-# INLINE lookupDefault #-} 75 | 76 | toList :: Key k => Map k v -> [(k, v)] 77 | toList = HM.toList 78 | {-# INLINE toList #-} 79 | 80 | keys :: Key k => Map k v -> [k] 81 | keys = HM.keys 82 | {-# INLINE keys #-} 83 | 84 | elems :: Map k v -> [v] 85 | elems = HM.elems 86 | {-# INLINE elems #-} 87 | 88 | insert :: Key k => k -> v -> Map k v -> Map k v 89 | insert = HM.insert 90 | {-# INLINE insert #-} 91 | 92 | insertWith :: Key k => (v -> v -> v) -> k -> v -> Map k v -> Map k v 93 | insertWith = HM.insertWith 94 | {-# INLINE insertWith #-} 95 | 96 | adjust :: Key k => (a -> a) -> k -> Map k a -> Map k a 97 | adjust = HM.adjust 98 | {-# INLINE adjust #-} 99 | 100 | update :: Key k => (a -> Maybe a) -> k -> Map k a -> Map k a 101 | update = HM.update 102 | {-# INLINE update #-} 103 | 104 | delete :: Key k => k -> Map k v -> Map k v 105 | delete = HM.delete 106 | {-# INLINE delete #-} 107 | 108 | alter :: Key k => (Maybe v -> Maybe v) -> k -> Map k v -> Map k v 109 | alter = HM.alter 110 | {-# INLINE alter #-} 111 | -------------------------------------------------------------------------------- /test/Main.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE DeriveAnyClass #-} 2 | 3 | module Main (main) where 4 | 5 | import Data.Hashable (Hashable) 6 | import Data.Proxy (Proxy (Proxy)) 7 | import Data.Text (Text) 8 | import GHC.Generics (Generic) 9 | import Test.QuickCheck (Arbitrary, Gen, arbitrary, choose, vectorOf) 10 | 11 | import qualified Data.Text as T 12 | import qualified Map.Laws.Hash as Hash 13 | import qualified Map.Laws.Int as Int 14 | import qualified Map.Laws.Ord as Ord 15 | 16 | 17 | -- | ShortText is a Text with length [0, 3] chosen "arbitrarily" 18 | newtype ShortText = ShortText 19 | { unShortText :: Text 20 | } deriving stock (Show, Generic) 21 | deriving newtype (Eq, Ord, Hashable) 22 | 23 | {- | Generates a Text with length [0, 3]. Choosing a small text speeds up the 24 | quickCheck tests. 25 | 26 | Note: do not make minimum larger than 0, empty texts are often edge cases. 27 | -} 28 | instance Arbitrary ShortText where 29 | arbitrary :: Gen ShortText 30 | arbitrary = ShortText . T.pack <$> (choose (0, 3) >>= flip vectorOf arbitrary) 31 | 32 | type K = Int 33 | type V = ShortText 34 | 35 | main :: IO () 36 | main = do 37 | Int.checkLaws (Proxy @Int) (Proxy @V) 38 | Ord.checkLaws (Proxy @K) (Proxy @V) 39 | Hash.checkLaws (Proxy @K) (Proxy @V) 40 | -- Prim.checkLaws (Proxy @K) (Proxy @V) 41 | --------------------------------------------------------------------------------