├── .gitignore ├── LICENSE ├── README.md ├── doc ├── Makefile ├── algo.tex ├── pearl.bib ├── pearl.tex ├── robust-catch.tex └── tree.tex └── src ├── BT ├── Safe.idr └── Unsafe.idr ├── Data ├── Array │ ├── ReadOnly.idr │ └── ReadOnly │ │ └── Unsafe.idr ├── Int │ └── Order.idr ├── Order.idr └── Order │ └── Extended.idr └── binary-search.ipkg /.gitignore: -------------------------------------------------------------------------------- 1 | *.ttc 2 | *.ttm 3 | *.ibc 4 | *.o 5 | *.log 6 | *.aux 7 | *.pdf 8 | *~ 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pearl-binary-search 2 | Functional Pearl: Certified Binary Search in a Read-Only Array 3 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | mkdir -p __build 3 | cp *.bib *.tex __build 4 | cd __build && latexmk -shell-escape -pdf -bibtex pearl.tex 5 | 6 | clean: 7 | rm -rf __build 8 | -------------------------------------------------------------------------------- /doc/algo.tex: -------------------------------------------------------------------------------- 1 | \begin{algorithm}[H] 2 | \SetKwInput{KwInput}{Input} 3 | \SetKwInput{KwOutput}{Output} % set the Output 4 | \DontPrintSemicolon 5 | 6 | \KwInput{Needle and array} 7 | \KwOutput{Is the needle in the array?} 8 | 9 | % Set Function Names 10 | \SetKwFunction{FSearch}{Search} 11 | % Write Function with word ``Function'' 12 | \SetKwProg{Fn}{Procedure}{:}{} 13 | \Fn{\FSearch{needle, array}}{ 14 | 15 | found := false\; 16 | begin := 0\; 17 | end := \texttt{size}(array)\; 18 | 19 | \; 20 | \While{\texttt{not}(found) \&\& begin < end} 21 | {\; 22 | middle := begin + (end - begin) / 2\; 23 | candidate := array[middle]\;\; 24 | 25 | \If{candidate = needle} {found := true} 26 | \ElseIf{needle < candidate}{end := middle} 27 | \Else{begin := middle + 1}\; 28 | } 29 | \KwRet{found}\; 30 | } 31 | \caption{Binary search in a sorted array} 32 | \label{algo:binarysearch} 33 | \end{algorithm} 34 | -------------------------------------------------------------------------------- /doc/pearl.bib: -------------------------------------------------------------------------------- 1 | @inproceedings{DBLP:conf/popl/Danielsson08, 2 | author = {Nils Anders Danielsson}, 3 | editor = {George C. Necula and 4 | Philip Wadler}, 5 | title = {Lightweight semiformal time complexity analysis for purely functional 6 | data structures}, 7 | booktitle = {Proceedings of the 35th {ACM} {SIGPLAN-SIGACT} Symposium on Principles 8 | of Programming Languages, {POPL} 2008, San Francisco, California, 9 | USA, January 7-12, 2008}, 10 | pages = {133--144}, 11 | publisher = {{ACM}}, 12 | year = {2008}, 13 | url = {https://doi.org/10.1145/1328438.1328457}, 14 | doi = {10.1145/1328438.1328457}, 15 | timestamp = {Tue, 06 Nov 2018 11:07:43 +0100}, 16 | biburl = {https://dblp.org/rec/conf/popl/Danielsson08.bib}, 17 | bibsource = {dblp computer science bibliography, https://dblp.org} 18 | } 19 | @MastersThesis{Morshtein:MScThesis:2020, 20 | author = {Shiri Morshtein}, 21 | title = {{Methods of Verifying Complexity Bounds ofAlgorithms using Dafny}}, 22 | school = {The Academic College Tel-Aviv Yaffo}, 23 | year = {2020}, 24 | } 25 | @inproceedings{workshop/fide/Morshtein21, 26 | author = {Shiri Morshtein and Ran Ettinger and Shmuel Tyszberowicz}, 27 | title = {Verifying Time Complexity of Binary Search using Dafny}, 28 | booktitle = {6th Workshop on Formal Integrated Development Environment}, 29 | year = {2021}, 30 | } 31 | @inproceedings{DBLP:conf/icfp/McBride14, 32 | author = {Conor Thomas McBride}, 33 | editor = {Johan Jeuring and 34 | Manuel M. T. Chakravarty}, 35 | title = {How to keep your neighbours in order}, 36 | booktitle = {Proceedings of the 19th {ACM} {SIGPLAN} international conference on 37 | Functional programming, Gothenburg, Sweden, September 1-3, 2014}, 38 | pages = {297--309}, 39 | publisher = {{ACM}}, 40 | year = {2014}, 41 | url = {https://doi.org/10.1145/2628136.2628163}, 42 | doi = {10.1145/2628136.2628163}, 43 | timestamp = {Tue, 06 Nov 2018 16:59:24 +0100}, 44 | biburl = {https://dblp.org/rec/conf/icfp/McBride14.bib}, 45 | bibsource = {dblp computer science bibliography, https://dblp.org} 46 | } 47 | @inproceedings{DBLP:conf/haskell/KiselyovI15, 48 | author = {Oleg Kiselyov and 49 | Hiromi Ishii}, 50 | editor = {Ben Lippmeier}, 51 | title = {Freer monads, more extensible effects}, 52 | booktitle = {Proceedings of the 8th {ACM} {SIGPLAN} Symposium on Haskell, Haskell 53 | 2015, Vancouver, BC, Canada, September 3-4, 2015}, 54 | pages = {94--105}, 55 | publisher = {{ACM}}, 56 | year = {2015}, 57 | url = {https://doi.org/10.1145/2804302.2804319}, 58 | doi = {10.1145/2804302.2804319}, 59 | timestamp = {Tue, 06 Nov 2018 16:58:22 +0100}, 60 | biburl = {https://dblp.org/rec/conf/haskell/KiselyovI15.bib}, 61 | bibsource = {dblp computer science bibliography, https://dblp.org} 62 | } 63 | @inproceedings{DBLP:conf/pldi/VollmerKRS0N19, 64 | author = {Michael Vollmer and 65 | Chaitanya Koparkar and 66 | Mike Rainey and 67 | Laith Sakka and 68 | Milind Kulkarni and 69 | Ryan R. Newton}, 70 | editor = {Kathryn S. McKinley and 71 | Kathleen Fisher}, 72 | title = {LoCal: a language for programs operating on serialized data}, 73 | year = {2019}, 74 | booktitle = {Proceedings of the 40th {ACM} {SIGPLAN} Conference on Programming 75 | Language Design and Implementation, {PLDI} 2019, Phoenix, AZ, USA, 76 | June 22-26, 2019}, 77 | pages = {48--62}, 78 | publisher = {{ACM}}, 79 | url = {https://doi.org/10.1145/3314221.3314631}, 80 | doi = {10.1145/3314221.3314631}, 81 | timestamp = {Fri, 06 Mar 2020 09:49:18 +0100}, 82 | biburl = {https://dblp.org/rec/conf/pldi/VollmerKRS0N19.bib}, 83 | bibsource = {dblp computer science bibliography, https://dblp.org} 84 | } 85 | @inproceedings{DBLP:conf/ifip2-1/AltenkirchM02, 86 | author = {Thorsten Altenkirch and 87 | Conor McBride}, 88 | title = {Generic Programming within Dependently Typed Programming}, 89 | booktitle = {Generic Programming, {IFIP} {TC2/WG2.1} Working Conference on Generic 90 | Programming, July 11-12, 2002, Dagstuhl, Germany}, 91 | pages = {1--20}, 92 | year = {2002}, 93 | crossref = {DBLP:conf/ifip2-1/2002}, 94 | timestamp = {Wed, 26 Feb 2003 14:25:56 +0100}, 95 | biburl = {https://dblp.org/rec/bib/conf/ifip2-1/AltenkirchM02}, 96 | bibsource = {dblp computer science bibliography, https://dblp.org} 97 | } 98 | @proceedings{DBLP:conf/ifip2-1/2002, 99 | editor = {Jeremy Gibbons and 100 | Johan Jeuring}, 101 | title = {Generic Programming, {IFIP} {TC2/WG2.1} Working Conference on Generic 102 | Programming, July 11-12, 2002, Dagstuhl, Germany}, 103 | series = {{IFIP} Conference Proceedings}, 104 | volume = {243}, 105 | publisher = {Kluwer}, 106 | year = {2003}, 107 | isbn = {1-4020-7374-7}, 108 | timestamp = {Wed, 26 Feb 2003 14:25:56 +0100}, 109 | biburl = {https://dblp.org/rec/bib/conf/ifip2-1/2002}, 110 | bibsource = {dblp computer science bibliography, https://dblp.org} 111 | } 112 | @article{DBLP:journals/jfp/McbrideP08, 113 | author = {Conor McBride and 114 | Ross Paterson}, 115 | title = {Applicative programming with effects}, 116 | journal = {J. Funct. Program.}, 117 | volume = {18}, 118 | number = {1}, 119 | pages = {1--13}, 120 | year = {2008}, 121 | url = {https://doi.org/10.1017/S0956796807006326}, 122 | doi = {10.1017/S0956796807006326}, 123 | timestamp = {Fri, 02 Nov 2018 09:31:48 +0100}, 124 | biburl = {https://dblp.org/rec/journals/jfp/McbrideP08.bib}, 125 | bibsource = {dblp computer science bibliography, https://dblp.org} 126 | } 127 | -------------------------------------------------------------------------------- /doc/pearl.tex: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gallais/pearl-binary-search/d9feed0c05aef339a6d7d745c128cddfb83ea76b/doc/pearl.tex -------------------------------------------------------------------------------- /doc/robust-catch.tex: -------------------------------------------------------------------------------- 1 | \makeatletter 2 | 3 | \newrobustcmd*\OrigExecuteMetaData[2][\jobname]{% 4 | \CatchFileBetweenTags\CatchFBT@tok{#1}{#2}% 5 | \global\expandafter\CatchFBT@tok\expandafter{% 6 | \expandafter}\the\CatchFBT@tok 7 | }%\OrigExecuteMetaData 8 | 9 | \newrobustcmd*\ChkExecuteMetaData[2][\jobname]{% 10 | \CatchFileBetweenTags\CatchFBT@tok{#1}{#2}% 11 | \edef\mytokens{\detokenize\expandafter{\the\CatchFBT@tok}} 12 | \ifx\mytokens\empty\PackageError{catchfilebetweentags}{the tag #2 is not found\MessageBreak in file #1 \MessageBreak called from \jobname.tex}{use a different tag}\fi% 13 | }%\ChkExecuteMetaData 14 | 15 | \renewrobustcmd*\ExecuteMetaData[2][\jobname]{% 16 | \ChkExecuteMetaData[#1]{#2}% 17 | \OrigExecuteMetaData[#1]{#2}% 18 | } 19 | 20 | \makeatother 21 | -------------------------------------------------------------------------------- /doc/tree.tex: -------------------------------------------------------------------------------- 1 | 2 | %<*search11> 3 | \begin{tikzpicture}[ampersand replacement=\&] 4 | % draw the content of the array 5 | \matrix (A) [matrix of nodes, nodes={draw, minimum size=8mm}, 6 | column sep=-\pgflinewidth]{ 7 | 2 \& 3 \& 5 \& 7 \& 11 \& 13 \& 17 \& 19 \& 23 \& 29\\}; 8 | 9 | % draw the elements, pointing at their source 10 | \draw (-2,3) circle (.3cm) node[align=center] {5}; 11 | \draw[->,thin,dashed] (-2,3-.3) -- (-2,0.4); 12 | 13 | \draw (-1.2,2) circle (.3cm) node[align=center] {7}; 14 | \draw[->,thin,dashed] (-1.2,2-.3) -- (-1.2,0.4); 15 | 16 | \draw (-.4,1) circle (.3cm) node[align=center] {11}; 17 | \draw[->,thin,dashed] (-.4,1-.3) -- (-.4,0.4); 18 | 19 | \draw (.4,4) circle (.3cm) node[align=center] {13}; 20 | \draw[->,thin,dashed] (.4,4-.3) -- (.4,0.4); 21 | 22 | % searching for 11 23 | \draw [->,red,thick] (.4-.3,4) to [out=180,in=90] (-2,3+.3); % 13 to 5 24 | \draw [->,red,thick] (-2+.3,3) to [out=0,in=90] (-1.2,2+.3); % 5 to 7 25 | \draw [->,red,thick] (-1.2+.3,2) to [out=0,in=90] (-.4,1+.3); % 7 to 11 26 | \draw [red,thick] (-.4,1) circle (.3cm) node[align=center] {11}; 27 | \end{tikzpicture} 28 | % 29 | 30 | %<*search31> 31 | \begin{tikzpicture}[ampersand replacement=\&] 32 | % draw the content of the array 33 | \matrix (A) [matrix of nodes, nodes={draw, minimum size=8mm}, 34 | column sep=-\pgflinewidth]{ 35 | 2 \& 3 \& 5 \& 7 \& 11 \& 13 \& 17 \& 19 \& 23 \& 29\\}; 36 | 37 | % draw the elements, pointing at their source 38 | \draw (.4,4) circle (.3cm) node[align=center] {13}; 39 | \draw[->,thin,dashed] (.4,4-.3) -- (.4,0.4); 40 | 41 | \draw (2,3) circle (.3cm) node[align=center] {19}; 42 | \draw[->,thin,dashed] (2,3-.3) -- (2,0.4); 43 | 44 | \draw (2.8,2) circle (.3cm) node[align=center] {23}; 45 | \draw[->,thin,dashed] (2.8,2-.3) -- (2.8,0.4); 46 | 47 | \draw (3.6,1) circle (.3cm) node[align=center] {29}; 48 | \draw[->,thin,dashed] (3.6,1-.3) -- (3.6,0.4); 49 | 50 | % searching for 31 51 | \draw [->,red,thick] (2.8+.3,2) to [out=0,in=90] (3.6,1+.3); % 23 to 29 52 | \draw [->,red,thick] (2+.3,3) to [out=0,in=90] (2.8,2+.3); % 19 to 23 53 | \draw [->,red,thick] (.4+.3,4) to [out=0,in=90] (2,3+.3); % 13 to 19 54 | \end{tikzpicture} 55 | % 56 | 57 | %<*searchall> 58 | \begin{tikzpicture}[ampersand replacement=\&] 59 | % draw the content of the array 60 | \matrix (A) [matrix of nodes, nodes={draw, minimum size=8mm}, 61 | column sep=-\pgflinewidth]{ 62 | 2 \& 3 \& 5 \& 7 \& 11 \& 13 \& 17 \& 19 \& 23 \& 29\\}; 63 | 64 | % draw the elements, pointing at their source 65 | \draw (-3.6,1) circle (.3cm) node [align=center] {2}; 66 | \draw[->,thin,dashed] (-3.6,1-.3) -- (-3.6,0.4); 67 | 68 | \draw (-2.8,2) circle (.3cm) node[align=center] {3}; 69 | \draw[->,thin,dashed] (-2.8,2-.3) -- (-2.8,0.4); 70 | 71 | \draw (-2,3) circle (.3cm) node[align=center] {5}; 72 | \draw[->,thin,dashed] (-2,3-.3) -- (-2,0.4); 73 | 74 | \draw (-1.2,2) circle (.3cm) node[align=center] {7}; 75 | \draw[->,thin,dashed] (-1.2,2-.3) -- (-1.2,0.4); 76 | 77 | \draw (-.4,1) circle (.3cm) node[align=center] {11}; 78 | \draw[->,thin,dashed] (-.4,1-.3) -- (-.4,0.4); 79 | 80 | \draw (.4,4) circle (.3cm) node[align=center] {13}; 81 | \draw[->,thin,dashed] (.4,4-.3) -- (.4,0.4); 82 | 83 | \draw (1.2,2) circle (.3cm) node[align=center] {17}; 84 | \draw[->,thin,dashed] (1.2,2-.3) -- (1.2,0.4); 85 | 86 | \draw (2,3) circle (.3cm) node[align=center] {19}; 87 | \draw[->,thin,dashed] (2,3-.3) -- (2,0.4); 88 | 89 | \draw (2.8,2) circle (.3cm) node[align=center] {23}; 90 | \draw[->,thin,dashed] (2.8,2-.3) -- (2.8,0.4); 91 | 92 | \draw (3.6,1) circle (.3cm) node[align=center] {29}; 93 | \draw[->,thin,dashed] (3.6,1-.3) -- (3.6,0.4); 94 | 95 | % all of the possible arcs 96 | \draw [thick] (2.8+.3,2) to [out=0,in=90] (3.6,1+.3); % 23 to 29 97 | \draw [thick] (2+.3,3) to [out=0,in=90] (2.8,2+.3); % 19 to 23 98 | \draw [thick] (2-.3,3) to [out=180,in=90] (1.2,2+.3); % 19 to 17 99 | \draw [thick] (.4+.3,4) to [out=0,in=90] (2,3+.3); % 13 to 19 100 | \draw [thick] (.4-.3,4) to [out=180,in=90] (-2,3+.3); % 13 to 5 101 | \draw [thick] (-1.2+.3,2) to [out=0,in=90] (-.4,1+.3); % 7 to 11 102 | \draw [thick] (-2+.3,3) to [out=0,in=90] (-1.2,2+.3); % 5 to 7 103 | \draw [thick] (-2-.3,3) to [out=180,in=90] (-2.8,2+.3); % 5 to 3 104 | \draw [thick] (-2.8-.3,2) to [out=180,in=90] (-3.6,1+.3); % 3 to 2 105 | \end{tikzpicture} 106 | % 107 | -------------------------------------------------------------------------------- /src/BT/Safe.idr: -------------------------------------------------------------------------------- 1 | module BT.Safe 2 | 3 | import Data.Buffer 4 | import Data.Int.Order 5 | import Data.DPair 6 | import Data.Array.ReadOnly 7 | import Data.Order 8 | import Data.Order.Extended 9 | 10 | %default total 11 | 12 | public export 13 | Rel : Type -> Type 14 | Rel a = a -> a -> Type 15 | 16 | ||| A type corresponding to a proof that a subarray is non-empty 17 | public export 18 | NonEmpty : SubArray arr -> Type 19 | NonEmpty = uncurry LT . boundaries 20 | 21 | ||| A type corresponding to a check on whether a subarray is empty 22 | public export 23 | EmptinessCheck : SubArray arr -> Type 24 | EmptinessCheck sub 25 | = Either (NonEmpty sub) (uncurry GTE (boundaries sub)) 26 | 27 | public export 28 | emptinessCheck : (sub : SubArray arr) -> EmptinessCheck sub 29 | emptinessCheck sub = 30 | let bnds : (Int, Int); bnds = boundaries sub in 31 | decide_LT_GTE (fst bnds) (snd bnds) 32 | 33 | mutual 34 | 35 | ||| The inductive type `BT'` proves that a given subarray is sorted. 36 | ||| @lt is the strict ordering used for this notion of being sorted 37 | ||| @arr is the underlying physical (read-only) array 38 | ||| @sub is the sub array we are focusing on 39 | ||| And the values in the subarray are contained between two (exclusive) bounds: 40 | ||| @lbV is the lower bound 41 | ||| @ubV is the upper bound 42 | ||| Finally, a tag: 43 | ||| @tag helps Idris see that the two constructors are disjoint 44 | data BT' : (lt : Rel a) -> 45 | {arr : Array a} -> (sub : SubArray arr) -> 46 | (lbV, ubV : Extended a) -> 47 | (tag : EmptinessCheck sub) -> 48 | Type where 49 | ||| If the range [lbI..ubI] is empty then the proof is trivial 50 | Empty : {0 sub : SubArray arr} -> (prf : _) -> BT' lt sub lbV ubV (Right prf) 51 | 52 | ||| Otherwise the expect the value at position `middle lbI ubI` 53 | ||| to be bounded by `lbV` and `ubV` and the subarrays to the 54 | ||| left and to the right of this middle point to be sorted too. 55 | Node : {a : Type} -> {lt : Rel a} -> {arr : Array a} -> {sub : SubArray arr} -> 56 | let bnds : (Int, Int); bnds = boundaries sub in 57 | (prf : LT (fst bnds) (snd bnds)) -> 58 | -- value in the middle position 59 | {v : a} -> ValueAt arr (middle sub) v -> 60 | {lbV, ubV : Extended a} -> 61 | ExtendedLT lt lbV (Lift v) -> ExtendedLT lt (Lift v) ubV -> 62 | let cuts : (SubArray arr, SubArray arr); cuts = cut sub (middleInRange prf) in 63 | -- each half is sorted too 64 | BT lt (fst cuts) lbV (Lift v) -> 65 | BT lt (snd cuts) (Lift v) ubV -> 66 | -- whole subarray is sorted 67 | BT' lt {arr} sub lbV ubV (Left prf) 68 | 69 | BT : (lt : Rel a) -> 70 | {arr : Array a} -> (sub : SubArray arr) -> 71 | (lbV, ubV : Extended a) -> 72 | Type 73 | BT lt sub lbV ubV = BT' lt sub lbV ubV (emptinessCheck sub) 74 | 75 | ------------------------------------------------------------------------ 76 | -- Safe search (with bound checking) 77 | 78 | public export 79 | leftSubArray : (sub : SubArray arr) -> NonEmpty sub -> SubArray arr 80 | leftSubArray sub prf = fst (cut sub (middleInRange prf)) 81 | 82 | public export 83 | rightSubArray : (sub : SubArray arr) -> NonEmpty sub -> SubArray arr 84 | rightSubArray sub prf = snd (cut sub (middleInRange prf)) 85 | 86 | data View : (sub : SubArray arr) -> {b : EmptinessCheck sub} -> 87 | BT' lt sub lbV ubV b -> Type where 88 | ViewEmpty : {0 arr : Array a} -> {0 sub : SubArray arr} -> (prf : _) -> View {arr} sub (Empty prf) 89 | ViewNode : {0 a : Type} -> {0 lt : Rel a} -> 90 | {0 arr : Array a} -> {sub : SubArray arr} -> 91 | {0 lbV, ubV : Extended a} -> 92 | (prf : LT _ _) -> (v : a) -> 93 | (0 val : ValueAt arr (middle sub) v) -> 94 | (0 lb : ExtendedLT lt lbV (Lift v)) -> 95 | (0 ub : ExtendedLT lt (Lift v) ubV) -> 96 | (0 left : BT lt (leftSubArray sub prf) lbV (Lift v)) -> 97 | (0 right : BT lt (rightSubArray sub prf) (Lift v) ubV) -> 98 | View sub (Node prf val lb ub left right) 99 | 100 | viewEmpty : {0 arr : Array a} -> {sub : SubArray arr} -> 101 | (prf : GTE _ _) -> (0 bt : BT' lt sub lbV ubV (Right prf)) -> View sub bt 102 | viewEmpty prf (Empty _) = ViewEmpty prf 103 | 104 | viewNode : {0 arr : Array a} -> {sub : SubArray arr} -> 105 | (prf : LT _ _) -> (0 bt : BT' lt sub lbV ubV (Left prf)) -> 106 | (v : a) -> (0 val : ValueAt arr (middle sub) v) -> 107 | View sub bt 108 | viewNode prf (Node _ val' lb ub left right) v val = 109 | rewrite uniqueValueAt val' val in 110 | ViewNode prf v 111 | (rewrite uniqueValueAt val val' in val') 112 | (rewrite uniqueValueAt val val' in lb) 113 | (rewrite uniqueValueAt val val' in ub) 114 | (rewrite uniqueValueAt val val' in left) 115 | (rewrite uniqueValueAt val val' in right) 116 | 117 | view : Storable a => 118 | {arr : Array a} -> {sub : SubArray arr} -> {tag : EmptinessCheck sub} -> 119 | (0 bt : BT' lt sub lbV ubV tag) -> 120 | IO (View sub bt) 121 | view {tag = Right p} bt = pure (viewEmpty p bt) 122 | view {tag = Left p} bt = do 123 | (Element v val) <- readValue sub (middle sub) (middleInRange p) 124 | pure (viewNode p bt v val) 125 | 126 | search : Storable a => 127 | -- looking for a needle 128 | (tri : (x, y : a) -> Trichotomous lt (===) (flip lt) x y) -> 129 | (needle : a) -> 130 | -- in a sorted subarray 131 | {arr : Array a} -> {sub : SubArray arr} -> {tag : EmptinessCheck sub} -> 132 | (0 bt : BT' lt sub lbV ubV tag) -> 133 | -- may succeed 134 | IO (Maybe (Subset Int (\ i => (InRange arr i, ValueAt arr i needle)))) 135 | search tri needle bt = case !(view bt) of 136 | ViewEmpty prf => pure Nothing 137 | ViewNode prf v val _ _ lft rgt => 138 | case tri needle v of 139 | MkLT _ _ _ => search tri needle lft 140 | MkEQ _ p _ => pure $ Just (Element _ (inSubRange (middleInRange prf), rewrite p in val)) 141 | MkGT _ _ _ => search tri needle rgt 142 | 143 | ------------------------------------------------------------------------ 144 | -- Decidability proof 145 | 146 | data Position : (sub : SubArray arr) -> NonEmpty sub -> Int -> Type where 147 | MkLT : InRange (leftSubArray sub prf) i -> Position sub prf i 148 | MkEQ : i === middle sub -> Position sub prf i 149 | MkGT : InRange (rightSubArray sub prf) i -> Position sub prf i 150 | 151 | position : (sub : SubArray arr) -> (prf : NonEmpty sub) -> 152 | {i : Int} -> InRange sub i -> Position sub prf i 153 | position sub prf inR = case trichotomous i (middle sub) of 154 | MkLT p _ _ => MkLT $ MkInterval (lowerBound inR) p 155 | MkEQ _ p _ => MkEQ (reflect p) 156 | MkGT _ _ p => MkGT $ MkInterval (suc_LT_LTE p) (upperBound inR) 157 | 158 | bounded : (tr : {x, y, z : a} -> lt x y -> lt y z -> lt x z) -> 159 | {sub : SubArray arr} -> {tag : _} -> BT' lt sub lbV ubV tag -> 160 | {i : Int} -> InRange sub i -> {v : a} -> ValueAt arr i v -> 161 | (ExtendedLT lt lbV (Lift v), ExtendedLT lt (Lift v) ubV) 162 | bounded tr (Empty prf) inR val 163 | = void $ irrefl $ trans_LTE_LT prf (intervalBounds inR) 164 | bounded tr (Node prf {v = v'} val' lb ub lft rgt) inR val = 165 | case position sub prf inR of 166 | MkLT inR' => let (ih1, ih2) := bounded tr lft inR' val 167 | in (ih1, trans tr ih2 ub) 168 | MkEQ Refl => rewrite uniqueValueAt val val' in (lb, ub) 169 | MkGT inR' => let (ih1, ih2) := bounded tr rgt inR' val 170 | in (trans tr lb ih1, ih2) 171 | 172 | increasing : (tr : {x, y, z : a} -> lt x y -> lt y z -> lt x z) -> 173 | {sub : SubArray arr} -> {tag : EmptinessCheck sub} -> BT' lt sub lbV ubV tag -> 174 | {i, j : Int} -> InRange sub i -> InRange sub j -> 175 | {v, w : _} -> ValueAt arr i v -> ValueAt arr j w -> 176 | LT i j -> lt v w 177 | increasing tr (Empty prf) iinR jinR vali valj p 178 | = void $ irrefl $ trans_LTE_LT prf (intervalBounds iinR) 179 | increasing tr (Node prf {v = v'} val' lb ub lft rgt) iinR jinR vali valj p = 180 | case (position sub prf iinR, position sub prf jinR) of 181 | (MkLT iinR', MkLT jinR') => increasing tr lft iinR' jinR' vali valj p 182 | (MkLT iinR', MkEQ Refl) => 183 | rewrite uniqueValueAt valj val' 184 | in LiftInversion (snd (bounded tr lft iinR' vali)) 185 | (MkLT iinR', MkGT jinR') => 186 | let bndL := snd (bounded tr lft iinR' vali) 187 | bndR := fst (bounded tr rgt jinR' valj) 188 | in LiftInversion (trans tr bndL bndR) 189 | (MkEQ Refl, MkLT jinR') => void $ irrefl $ trans p (upperBound jinR') 190 | (MkEQ Refl, MkEQ Refl) => void $ irrefl p 191 | (MkEQ Refl, MkGT jinR') => 192 | rewrite uniqueValueAt vali val' 193 | in LiftInversion (fst (bounded tr rgt jinR' valj)) 194 | (MkGT iinR', MkLT jinR') => void $ irrefl $ 195 | let 0 q : LT j (middle sub) := upperBound jinR' 196 | 0 r : LT (middle sub) (middle sub + 1) := sucBounded (upperBound (middleInRange prf)) 197 | 0 s : LTE (middle sub + 1) i := lowerBound iinR' 198 | in trans p (trans q (trans_LT_LTE r s)) 199 | (MkGT iinR', MkEQ Refl) => void $ irrefl $ 200 | let 0 q : LT (middle sub) (middle sub + 1) := sucBounded (upperBound (middleInRange prf)) 201 | 0 r : LTE (middle sub + 1) i := lowerBound iinR' 202 | in trans q (trans_LTE_LT r p) 203 | (MkGT iinR', MkGT jinR') => increasing tr rgt iinR' jinR' vali valj p 204 | 205 | decide' : Storable a => 206 | -- looking for a needle 207 | (irr : {x : a} -> Not (lt x x)) -> 208 | (tr : {x, y, z : a} -> lt x y -> lt y z -> lt x z) -> 209 | (tri : (x, y : a) -> Trichotomous lt (===) (flip lt) x y) -> 210 | (needle : a) -> 211 | -- in a sorted subarray 212 | {arr : Array a} -> {sub : SubArray arr} -> {tag : EmptinessCheck sub} -> 213 | (0 bt : BT' lt sub lbV ubV tag) -> 214 | -- is decidable 215 | IO (Dec (Subset Int (\ i => (InRange sub i, ValueAt arr i needle)))) 216 | decide' irr tr tri needle bt = case !(view bt) of 217 | ViewEmpty prf => pure $ No \ (Element i p) => 218 | void $ irrefl $ trans_LTE_LT prf (intervalBounds (fst p)) 219 | ViewNode prf v val _ _ lft rgt => 220 | case tri needle v of 221 | MkLT p _ _ => case !(decide' irr tr tri needle lft) of 222 | Yes (Element i q) => do 223 | let 0 inR : InRange sub i 224 | := expandIntervalRight (fst q) (inject_LT_LTE (upperBound (middleInRange prf))) 225 | pure $ Yes (Element i (inR, snd q)) 226 | No contra => pure $ No $ \ (Element i q) => void $ case position sub prf (fst q) of 227 | MkLT inR => contra (Element i (inR, snd q)) -- TODO 228 | MkEQ Refl => irr (replace {p = lt needle} (uniqueValueAt val (snd q)) p) 229 | MkGT inR => 230 | let r : lt v needle := LiftInversion (fst (bounded tr rgt inR (snd q))) 231 | in irr (tr p r) 232 | MkEQ _ p _ => pure $ Yes (Element _ (middleInRange prf, rewrite p in val)) 233 | MkGT _ _ p => case !(decide' irr tr tri needle rgt) of 234 | Yes (Element i p) => do 235 | let 0 lte : LTE (fst (begin sub)) (middle sub + 1) 236 | := let (MkInterval p q) := middleInRange prf in trans p (inject_LT_LTE (sucBounded q)) 237 | 0 inR : InRange sub i 238 | := expandIntervalLeft lte (fst p) 239 | pure $ Yes (Element i (inR, snd p)) 240 | No contra => pure $ No $ \ (Element i q) => void $ case position sub prf (fst q) of 241 | MkLT inR => 242 | let r : lt needle v := LiftInversion (snd (bounded tr lft inR (snd q))) 243 | in irr (tr p r) 244 | MkEQ Refl => irr (replace {p = lt v} (uniqueValueAt (snd q) val) p) 245 | MkGT inR => contra (Element i (inR, snd q)) 246 | 247 | 248 | decide : Storable a => 249 | -- provided the order has good properties 250 | (irr : {x : a} -> Not (lt x x)) -> 251 | (tr : {x, y, z : a} -> lt x y -> lt y z -> lt x z) -> 252 | (tri : (x, y : a) -> Trichotomous lt (===) (flip lt) x y) -> 253 | -- looking a needle up 254 | (needle : a) -> 255 | -- in a sorted array 256 | (arr : Array a) -> (0 bt : BT lt (whole arr) lbV ubV) -> 257 | -- is decidable 258 | IO (Dec (Subset Int (\ i => (InRange arr i, ValueAt arr i needle)))) 259 | decide irr tr tri needle arr bt = decide' irr tr tri needle bt 260 | -------------------------------------------------------------------------------- /src/BT/Unsafe.idr: -------------------------------------------------------------------------------- 1 | module BT.Unsafe 2 | 3 | import Data.Buffer 4 | import Data.Int.Order 5 | import Data.DPair 6 | import Data.Array.ReadOnly 7 | import Data.Array.ReadOnly.Unsafe 8 | import Data.Order 9 | import Data.Order.Extended 10 | 11 | %default total 12 | 13 | public export 14 | Rel : Type -> Type 15 | Rel a = a -> a -> Type 16 | 17 | mutual 18 | 19 | ||| The inductive type `BT'` proves that a given subarray is sorted. 20 | ||| @lt is the strict ordering used for this notion of being sorted 21 | ||| @arr is the underlying physical (read-only) array 22 | ||| The subarray is contained between two bounds: 23 | ||| @lbI is the (inclusive) lower bound 24 | ||| @ubI is the (exclusive) upper bound 25 | ||| And the values in the subarray thus delimited are contained between two 26 | ||| (exclusive) bounds: 27 | ||| @lbV is the lower bound 28 | ||| @ubV is the upper bound 29 | ||| Finally, a tag: 30 | ||| @tag helps Idris see that the two constructors are disjoint 31 | 32 | data BT' : (lt : Rel a) -> 33 | (arr : Array a) -> 34 | (lbI : Int) -> (lbV : Extended a) -> 35 | (ubI : Int) -> (ubV : Extended a) -> 36 | (tag : Either (LT lbI ubI) (GTE lbI ubI)) -> 37 | Type where 38 | ||| If the range [lbI..ubI] is empty then the proof is trivial 39 | Empty : (prf : GTE lbI ubI) -> BT' lt arr lbI lbV ubI ubV (Right prf) 40 | 41 | ||| Otherwise the expect the value at position `middle lbI ubI` 42 | ||| to be bounded by `lbV` and `ubV` and the subarrays to the 43 | ||| left and to the right of this middle point to be sorted too. 44 | Node : (prf : LT lbI ubI) -> 45 | -- value in the middle position 46 | ValueAt arr (middle lbI ubI) v -> 47 | ExtendedLT lt lbV (Lift v) -> ExtendedLT lt (Lift v) ubV -> 48 | -- each half is sorted too 49 | BT lt arr lbI lbV (middle lbI ubI) (Lift v) -> 50 | BT lt arr (middle lbI ubI + 1) (Lift v) ubI ubV -> 51 | -- whole subarray is sorted 52 | BT' lt arr lbI lbV ubI ubV (Left prf) 53 | 54 | BT : (lt : Rel a) -> 55 | (arr : Array a) -> 56 | (lbI : Int) -> (lbV : Extended a) -> 57 | (ubI : Int) -> (ubV : Extended a) -> 58 | Type 59 | BT lt arr lbI lbV ubI ubV = BT' lt arr lbI lbV ubI ubV (decide_LT_GTE lbI ubI) 60 | 61 | data View : BT' lt arr lbI lbV ubI ubV b -> Type where 62 | ViewEmpty : {0 lt : Rel a} -> (prf : GTE lbI ubI) -> View (Empty {lt} prf) 63 | ViewNode : (prf : LT lbI ubI) -> (v : a) -> 64 | (0 val : ValueAt arr (middle lbI ubI) v) -> 65 | (0 lb : ExtendedLT lt lbV (Lift v)) -> 66 | (0 ub : ExtendedLT lt (Lift v) ubV) -> 67 | (0 left : BT lt arr lbI lbV (middle lbI ubI) (Lift v)) -> 68 | (0 right : BT lt arr (middle lbI ubI + 1) (Lift v) ubI ubV) -> 69 | View (Node prf val lb ub left right) 70 | 71 | 72 | viewEmpty : (prf : GTE lbI ubI) -> (0 bt : BT' lt arr lbI lbV ubI ubV (Right prf)) -> View bt 73 | viewEmpty prf (Empty _) = ViewEmpty prf 74 | 75 | viewNode : (prf : _) -> (0 bt : BT' lt arr lbI lbV ubI ubV (Left prf)) -> 76 | (v : a) -> (0 val : ValueAt arr (middle lbI ubI) v) -> 77 | View bt 78 | viewNode prf (Node _ val' lb ub left right) v val = 79 | rewrite uniqueValueAt val' val in 80 | ViewNode prf v 81 | (rewrite uniqueValueAt val val' in val') 82 | (rewrite uniqueValueAt val val' in lb) 83 | (rewrite uniqueValueAt val val' in ub) 84 | (rewrite uniqueValueAt val val' in left) 85 | (rewrite uniqueValueAt val val' in right) 86 | 87 | view : (HasIO io, Storable a) => 88 | {arr : Array a} -> {lbI, ubI : Int} -> 89 | {tag : Either (LT lbI ubI) (GTE lbI ubI)} -> 90 | (0 bt : BT' lt arr lbI lbV ubI ubV tag) -> 91 | io (View bt) 92 | view {tag = Right p} bt = pure (viewEmpty p bt) 93 | view {tag = Left p} bt = do 94 | (Element v val) <- unsafeReadValue arr (middle lbI ubI) 95 | pure (viewNode p bt v val) 96 | 97 | search : (Storable a) => 98 | -- looking for a needle 99 | (tri : (x, y : a) -> Trichotomous lt (===) (flip lt) x y) -> 100 | (needle : a) -> 101 | -- in a sorted array 102 | {arr : Array a} -> 103 | {lbI : Int} -> {lbV : Extended a} -> 104 | {ubI : Int} -> {ubV : Extended a} -> 105 | {tag : Either (LT lbI ubI) (GTE lbI ubI)} -> 106 | (0 bt : BT' lt arr lbI lbV ubI ubV tag) -> 107 | -- may succeed 108 | IO (Maybe (Subset Int (\ i => ValueAt arr i needle))) 109 | search tri needle bt = case !(view bt) of 110 | ViewEmpty prf => pure Nothing 111 | ViewNode _ v val _ _ lft rgt => case tri needle v of 112 | MkLT _ _ _ => search tri needle lft 113 | MkEQ _ p _ => pure $ Just (Element (middle lbI ubI) (rewrite p in val)) 114 | MkGT _ _ _ => search tri needle rgt 115 | -------------------------------------------------------------------------------- /src/Data/Array/ReadOnly.idr: -------------------------------------------------------------------------------- 1 | module Data.Array.ReadOnly 2 | 3 | import Data.Buffer 4 | import Data.DPair 5 | import Data.Int.Order 6 | 7 | %default total 8 | 9 | public export 10 | PosInt : Type 11 | PosInt = Subset Int (LTE 0) 12 | 13 | namespace PosInt 14 | 15 | public export 16 | InRange : PosInt -> Int -> Type 17 | InRange size = Interval True False 0 (fst size) 18 | 19 | ------------------------------------------------------------------------ 20 | -- Arrays 21 | 22 | ||| Read-only array of elements of type `a` 23 | ||| @size is the size of the Buffer. It should be safe to access any element 24 | ||| between 0 and `size` 25 | ||| @buffer contains the actual array 26 | ||| We do not export the constructor so that users may not unsafely manufacture arrays. 27 | export 28 | record Array (a : Type) where 29 | constructor MkArray 30 | size : PosInt 31 | buffer : Buffer 32 | 33 | ||| A sub-array is delimited by two bounds 34 | ||| @begin (inclusive) for the beginning (0 for the full array) 35 | ||| @end (exclusive) for the end (size arr for the full array) 36 | ||| It is non empty if and only if `LT begin end` 37 | public export 38 | record SubArray {a : Type} (arr : Array a) where 39 | constructor MkSubArray 40 | begin : Subset Int (ClosedInterval 0 (fst (size arr))) 41 | end : Subset Int (ClosedInterval 0 (fst (size arr))) 42 | 43 | public export 44 | boundaries : SubArray arr -> (Int, Int) 45 | boundaries sub = (fst (begin sub), fst (end sub)) 46 | 47 | public export 48 | middle : SubArray arr -> Int 49 | middle = uncurry middle . boundaries 50 | 51 | public export 52 | whole : (arr : Array a) -> SubArray arr 53 | whole arr = 54 | let 0 p : LTE 0 (fst (size arr)); p = snd (size arr) 55 | in MkSubArray (Element 0 (lbInClosedInterval p)) (Element _ (ubInClosedInterval p)) 56 | 57 | ------------------------------------------------------------------------ 58 | -- Array ranges 59 | 60 | namespace Array 61 | 62 | ||| We do not export the type publically so that the goals are more readable 63 | public export 64 | InRange : Array a -> (Int -> Type) 65 | InRange arr = Interval True False 0 (fst (size arr)) 66 | 67 | namespace SubArray 68 | 69 | ||| We do not export the type publically so that the goals are more readable 70 | public export 71 | InRange : SubArray arr -> (Int -> Type) 72 | InRange sub = Interval True False (fst (begin sub)) (fst (end sub)) 73 | 74 | ||| Theorem: sub range inclusion 75 | ||| If a value is in range for a subarray then it is in range for the full array 76 | export 77 | 0 inSubRange : {sub : SubArray arr} -> InRange sub i -> InRange arr i 78 | inSubRange 79 | {sub = MkSubArray (Element b (MkInterval prfb _)) 80 | (Element e (MkInterval _ prfe)) 81 | } (MkInterval isLB isUB) 82 | = MkInterval (trans prfb isLB) (trans_LT_LTE isUB prfe) 83 | 84 | export 85 | middleInRange : {sub : SubArray arr} -> 86 | uncurry LT (boundaries sub) -> InRange sub (middle sub) 87 | middleInRange = middleInInterval 88 | 89 | public export 90 | cut : {i : Int} -> (sub : SubArray arr) -> (0 _ : InRange sub i) -> (SubArray arr, SubArray arr) 91 | cut sub inR 92 | = let 0 inR' : InRange arr i; inR' = inSubRange inR in 93 | ( MkSubArray (begin sub) (Element i (inClosedInterval inR')) 94 | , MkSubArray (Element (i + 1) (inClosedInterval (sucInterval inR'))) (end sub) 95 | ) 96 | 97 | ------------------------------------------------------------------------ 98 | -- Array value at position 99 | 100 | ||| Predicate specifying what the value in a given read-only array is at a 101 | ||| given index. The constructor for this predicate is proof-free because 102 | ||| the array is effectively external. It is not exported so that users may 103 | ||| craft their own, invalid, proofs. 104 | export 105 | data ValueAt : (arr : Array a) -> (i : Int) -> a -> Type where 106 | MkValueAt : ValueAt arr i v 107 | 108 | ||| Magic function stating that the predicate guarantees values are unique. 109 | export 110 | uniqueValueAt : ValueAt {a} arr i v -> ValueAt arr i w -> v === w 111 | uniqueValueAt = believe_me (the (v === v) Refl) 112 | 113 | ------------------------------------------------------------------------ 114 | -- Reading and writing values 115 | 116 | ||| The only mode of interaction with a read-only array: you may read it if 117 | ||| you are using an index. 118 | export 119 | interface Storable a where 120 | 121 | unsafeGetValueAt : HasIO io => Buffer -> Int -> io a 122 | unsafeCreateBuffer : HasIO io => (size : Int) -> (Int -> a) -> io Buffer 123 | 124 | public export 125 | IsTabulationOf : (f : (i : Int) -> InRange size i -> a) -> Array a -> Type 126 | IsTabulationOf f arr = (i : Int) -> (prf : InRange size i) -> ValueAt arr i (f i prf)) 127 | 128 | export 129 | initialise : (HasIO io, Storable a) => 130 | (size : PosInt) -> 131 | (f : (i : Int) -> InRange size i -> a) -> 132 | io (Subset (Array a) (IsTabulationOf f)) 133 | initialise s@(Element size _) f 134 | = do buffer <- unsafeCreateBuffer size f' 135 | pure $ Element (MkArray s buffer) (\ _,_ => MkValueAt) 136 | 137 | where 138 | f' : Int -> a 139 | f' i = case decide 0 size i of 140 | Yes prf => f i prf 141 | No contra => assert_total $ idris_crash "Error: invalid access by unsafeCreateBuffer" 142 | 143 | namespace Array 144 | 145 | ||| The blessed mode of interaction with a read-only array: not only do you 146 | ||| read the value but you get your hands on a proof that it is indeed the 147 | ||| value at the index you requested. 148 | export 149 | readValue : (HasIO io, Storable a) => (arr : Array a) -> 150 | (i : Int) -> (0 prf : InRange arr i) -> 151 | io (Subset a (ValueAt arr i)) 152 | readValue arr i p = map (\ v => Element v MkValueAt) $ unsafeGetValueAt (buffer arr) i 153 | 154 | namespace SubArray 155 | 156 | ||| The blessed mode of interaction with a read-only subarray: not only do you 157 | ||| read the value but you get your hands on a proof that it is indeed the 158 | ||| value at the index you requested. 159 | export 160 | readValue : (HasIO io, Storable a) => {arr : Array a} -> (sub : SubArray arr) -> 161 | (i : Int) -> (0 prf : InRange sub i) -> 162 | io (Subset a (ValueAt arr i)) 163 | readValue sub i p = readValue arr i (inSubRange p) 164 | -------------------------------------------------------------------------------- /src/Data/Array/ReadOnly/Unsafe.idr: -------------------------------------------------------------------------------- 1 | module Data.Array.ReadOnly.Unsafe 2 | 3 | import Data.Array.ReadOnly 4 | import Data.DPair 5 | 6 | export 7 | unsafeReadValue : (HasIO io, Storable a) => 8 | (arr : Array a) -> (i : Int) -> io (Subset a (ValueAt arr i)) 9 | unsafeReadValue arr i = map (\ v => Element v MkValueAt) $ unsafeGetValueAt arr i 10 | -------------------------------------------------------------------------------- /src/Data/Int/Order.idr: -------------------------------------------------------------------------------- 1 | module Data.Int.Order 2 | 3 | import Data.Bits 4 | import Data.Order 5 | import Data.DPair 6 | 7 | %default total 8 | 9 | %hide Nat.LT 10 | %hide Nat.LTE 11 | %hide Nat.GT 12 | 13 | 14 | ------------------------------------------------------------------------ 15 | -- Prelude 16 | 17 | -- Because we are going to essentially postulate that some equality hold 18 | -- using `believe_me`, we better be careful about the kind of proofs we 19 | -- trust. 20 | export 21 | strictRefl : a === b -> Lazy c -> c 22 | strictRefl Refl p = p 23 | 24 | -- Do NOT re-export 25 | unsafeRefl : {0 a, b : t} -> a === b 26 | unsafeRefl = believe_me (the (a === a) Refl) 27 | 28 | ------------------------------------------------------------------------ 29 | -- LT 30 | 31 | namespace LT 32 | 33 | public export 34 | data LT : Int -> Int -> Type where 35 | MkLT : (a < b) === True -> LT a b 36 | 37 | export 38 | strictLT : LT a b -> Lazy c -> c 39 | strictLT (MkLT p) c = strictRefl p c 40 | 41 | export 42 | decide : (a, b : Int) -> Dec (LT a b) 43 | decide a b with (the (test : Bool ** (a < b) === test) (a < b ** Refl)) 44 | decide a b | (True ** p) = Yes (MkLT p) 45 | decide a b | (False ** p) = No (\ (MkLT q) => absurd (trans (sym p) q)) 46 | 47 | export 48 | trans : LT a b -> LT b c -> LT a (the Int c) 49 | trans p q = strictLT p $ strictLT q $ MkLT unsafeRefl 50 | 51 | export 52 | irrefl : Not (LT a a) 53 | irrefl p = strictLT p $ the Void 54 | $ assert_total $ idris_crash "IMPOSSIBLE: LT is irreflexive" 55 | 56 | public export 57 | GT : Int -> Int -> Type 58 | GT = flip LT 59 | 60 | export 61 | LT_not_GT : LT a b -> Not (GT a b) 62 | LT_not_GT p q = irrefl (trans p q) 63 | 64 | export 65 | GT_not_LT : GT a b -> Not (LT a b) 66 | GT_not_LT = flip LT_not_GT 67 | 68 | ------------------------------------------------------------------------ 69 | -- EQ 70 | 71 | namespace EQ 72 | 73 | public export 74 | data EQ : Int -> Int -> Type where 75 | MkEQ : (a == b) === True -> EQ a b 76 | 77 | export 78 | strictEQ : EQ a b -> Lazy c -> c 79 | strictEQ (MkEQ p) c = strictRefl p c 80 | 81 | export 82 | decide : (a, b : Int) -> Dec (EQ a b) 83 | decide a b with (the (test : Bool ** (a == b) === test) (a == b ** Refl)) 84 | decide a b | (True ** p) = Yes (MkEQ p) 85 | decide a b | (False ** p) = No (\ (MkEQ q) => absurd (trans (sym p) q)) 86 | 87 | export 88 | refl : EQ a a 89 | refl = MkEQ unsafeRefl 90 | 91 | export 92 | elimEQ : (0 p : Int -> Type) -> EQ a b -> p a -> p b 93 | elimEQ _ p v = strictEQ p $ believe_me v 94 | 95 | export 96 | reflect : EQ a b -> a === b 97 | reflect p = elimEQ (\ b => a === b) p Refl 98 | 99 | export 100 | sym : EQ a b -> EQ b a 101 | sym p = elimEQ (\ b => EQ b a) p refl 102 | 103 | export 104 | trans : EQ a b -> EQ b c -> EQ a c 105 | trans p q = elimEQ (\ b => EQ b c) (sym p) q 106 | 107 | export 108 | trans_LT_EQ : LT a b -> EQ b c -> LT a c 109 | trans_LT_EQ p q = elimEQ (LT a) q p 110 | 111 | export 112 | trans_EQ_LT : EQ a b -> LT b c -> LT a c 113 | trans_EQ_LT p q = elimEQ (\ b => LT b c) (sym p) q 114 | 115 | export 116 | LT_not_EQ : LT a b -> Not (EQ a b) 117 | LT_not_EQ p q = irrefl (trans_LT_EQ p (sym q)) 118 | 119 | export 120 | EQ_not_LT : EQ a b -> Not (LT a b) 121 | EQ_not_LT = flip LT_not_EQ 122 | 123 | export 124 | EQ_not_GT : EQ a b -> Not (GT a b) 125 | EQ_not_GT = EQ_not_LT . sym 126 | 127 | export 128 | GT_not_EQ : GT a b -> Not (EQ a b) 129 | GT_not_EQ = flip EQ_not_GT 130 | 131 | ------------------------------------------------------------------------ 132 | -- LTE 133 | 134 | namespace LTE 135 | 136 | public export 137 | data LTE : Int -> Int -> Type where 138 | MkLT : (a < b) === True -> LTE a b 139 | MkEQ : (a == b) === True -> LTE a b 140 | 141 | export 142 | decide : (a, b : Int) -> Dec (LTE a b) 143 | decide a b with (LT.decide a b) 144 | decide a b | Yes (MkLT p) = Yes (MkLT p) 145 | decide a b | No notLT with (EQ.decide a b) 146 | decide a b | No notLT | Yes (MkEQ p) = Yes (MkEQ p) 147 | decide a b | No notLT | No notEQ = No $ \ case 148 | MkLT p => notLT (MkLT p) 149 | MkEQ p => notEQ (MkEQ p) 150 | 151 | export 152 | refl : LTE a a 153 | refl = MkEQ unsafeRefl 154 | 155 | export 156 | trans_LT_LTE : LT a b -> LTE b c -> LT a c 157 | trans_LT_LTE p (MkLT q) = trans p (MkLT q) 158 | trans_LT_LTE p (MkEQ q) = trans_LT_EQ p (MkEQ q) 159 | 160 | export 161 | trans_LTE_LT : LTE a b -> LT b c -> LT a c 162 | trans_LTE_LT (MkLT p) q = trans (MkLT p) q 163 | trans_LTE_LT (MkEQ p) q = trans_EQ_LT (MkEQ p) q 164 | 165 | export 166 | inject_LT_LTE : LT a b -> LTE a b 167 | inject_LT_LTE (MkLT p) = MkLT p 168 | 169 | export 170 | inject_EQ_LTE : EQ a b -> LTE a b 171 | inject_EQ_LTE (MkEQ p) = MkEQ p 172 | 173 | export 174 | trans : LTE a b -> LTE b c -> LTE a c 175 | trans (MkLT p) q = inject_LT_LTE (trans_LT_LTE (MkLT p) q) 176 | trans p (MkLT q) = inject_LT_LTE (trans_LTE_LT p (MkLT q)) 177 | trans (MkEQ p) (MkEQ q) = inject_EQ_LTE (trans (MkEQ p) (MkEQ q)) 178 | 179 | export 180 | strictLTE : LTE a b -> Lazy c -> c 181 | strictLTE (MkLT p) q = strictRefl p q 182 | strictLTE (MkEQ p) q = strictRefl p q 183 | 184 | public export 185 | GTE : Int -> Int -> Type 186 | GTE = flip LTE 187 | 188 | export 189 | caseLTE : LTE a b -> Either (LT a b) (EQ a b) 190 | caseLTE (MkLT p) = Left (MkLT p) 191 | caseLTE (MkEQ p) = Right (MkEQ p) 192 | 193 | ------------------------------------------------------------------------ 194 | -- Trichotomy and other decidability results 195 | 196 | export 197 | trichotomous : (a, b : Int) -> Trichotomous LT EQ GT a b 198 | trichotomous a b with (LTE.decide a b) 199 | trichotomous a b | Yes (MkLT p) = let lt = MkLT p in MkLT lt (LT_not_EQ lt) (LT_not_GT lt) 200 | trichotomous a b | Yes (MkEQ p) = let eq = MkEQ p in MkEQ (EQ_not_LT eq) eq (EQ_not_GT eq) 201 | trichotomous a b | No notLTE = let gt = MkLT unsafeRefl in MkGT (GT_not_LT gt) (GT_not_EQ gt) gt 202 | 203 | export 204 | decide_LT_GTE : (a, b : Int) -> Either (LT a b) (GTE a b) 205 | decide_LT_GTE a b with (trichotomous a b) 206 | decide_LT_GTE a b | MkLT lt _ _ = Left lt 207 | decide_LT_GTE a b | MkEQ _ eq _ = Right (inject_EQ_LTE (sym eq)) 208 | decide_LT_GTE a b | MkGT _ _ gt = Right (inject_LT_LTE gt) 209 | 210 | ------------------------------------------------------------------------ 211 | -- Some properties 212 | 213 | export 214 | suc_LT_LTE : {a, b : Int} -> LT a b -> LTE (a + 1) b 215 | suc_LT_LTE p with (the (test : Bool ** (a + 1 == b) === test) (a + 1 == b ** Refl)) 216 | suc_LT_LTE p | (True ** q) = MkEQ q 217 | suc_LT_LTE p | (False ** _) = MkLT unsafeRefl 218 | 219 | export 220 | sucBounded : LT a b -> LT a (a + 1) 221 | sucBounded p = strictLT p $ MkLT unsafeRefl 222 | 223 | export 224 | pred_LT_LTE : {a, b : Int} -> LT a b -> LTE a (b - 1) 225 | pred_LT_LTE p with (the (test : Bool ** (a == b - 1) === test) (a == b - 1 ** Refl)) 226 | pred_LT_LTE p | (True ** q) = MkEQ q 227 | pred_LT_LTE p | (False ** _) = MkLT unsafeRefl 228 | 229 | ------------------------------------------------------------------------ 230 | -- Intervals 231 | 232 | ||| And interval is an `Int -> Type` predicate characterised by 4 parameters: 233 | ||| @lbI for whether the lower bound is inclusive 234 | ||| @ubI for whether the upper bound is inclusive 235 | ||| @lb for the lower bound 236 | ||| @ub for the upper bound 237 | ||| @i is the integer being talked about 238 | public export 239 | record Interval (lbI, ubI : Bool) (lb, ub : Int) (i : Int) where 240 | constructor MkInterval 241 | lowerBound : (ifThenElse lbI LTE LT) lb i 242 | upperBound : (ifThenElse ubI LTE LT) i ub 243 | 244 | namespace Interval 245 | 246 | export 247 | decide : {lbI, ubI : Bool} -> (lb, ub, i : Int) -> Dec (Interval lbI ubI lb ub i) 248 | decide lb ub i = case decide lbI lb i of 249 | No contra => No (contra . lowerBound) 250 | Yes p => case decide ubI i ub of 251 | No contra => No (contra . upperBound) 252 | Yes q => Yes (MkInterval p q) 253 | 254 | where 255 | 256 | decide : (b : Bool) -> (v, w : Int) -> Dec (ifThenElse b LTE LT v w) 257 | decide True = LTE.decide 258 | decide False = LT.decide 259 | 260 | ||| If an interval is non-empty then we can conclude that the lower bound is less 261 | ||| than (or equal to potentially) the upper bound 262 | export 263 | intervalBounds : {lbI, ubI : Bool} -> Interval lbI ubI lb ub i -> 264 | ifThenElse (lbI && ubI) LTE LT lb ub 265 | intervalBounds {lbI = True} {ubI = True} i = LTE.trans (lowerBound i) (upperBound i) 266 | intervalBounds {lbI = False} {ubI = True} i = trans_LT_LTE (lowerBound i) (upperBound i) 267 | intervalBounds {lbI = True} {ubI = False} i = trans_LTE_LT (lowerBound i) (upperBound i) 268 | intervalBounds {lbI = False} {ubI = False} i = trans (lowerBound i) (upperBound i) 269 | 270 | export 271 | expandIntervalLeft : {lbI : Bool} -> LTE a lb -> Interval lbI ubI lb ub i -> Interval lbI ubI a ub i 272 | expandIntervalLeft {lbI = True} p (MkInterval isLB isUB) = MkInterval (trans p isLB) isUB 273 | expandIntervalLeft {lbI = False} p (MkInterval isLB isUB) = MkInterval (trans_LTE_LT p isLB) isUB 274 | 275 | export 276 | expandIntervalRight : {ubI : Bool} -> Interval lbI ubI lb ub i -> LTE ub a -> Interval lbI ubI lb a i 277 | expandIntervalRight {ubI = True} (MkInterval isLB isUB) p = MkInterval isLB (trans isUB p) 278 | expandIntervalRight {ubI = False} (MkInterval isLB isUB) p = MkInterval isLB (trans_LT_LTE isUB p) 279 | 280 | public export 281 | ClosedInterval : (lb, ub : Int) -> (Int -> Type) 282 | ClosedInterval = Interval True True 283 | 284 | export 285 | inClosedInterval : {lbI, ubI : Bool} -> Interval lbI ubI lb ub i -> ClosedInterval lb ub i 286 | inClosedInterval (MkInterval isLB isUB) = MkInterval (relax _ isLB) (relax _ isUB) where 287 | 288 | relax : (b : Bool) -> ifThenElse b LTE LT v w -> LTE v w 289 | relax True p = p 290 | relax False p = inject_LT_LTE p 291 | 292 | export 293 | sucInterval : {i, ub : Int} -> Interval True False lb ub i -> Interval False True lb ub (i + 1) 294 | sucInterval (MkInterval isLB isUB) 295 | = MkInterval (strictLTE isLB (MkLT unsafeRefl)) (suc_LT_LTE isUB) 296 | 297 | export 298 | lbInClosedInterval : LTE lb ub -> ClosedInterval lb ub lb 299 | lbInClosedInterval = MkInterval refl 300 | 301 | export 302 | ubInClosedInterval : LTE lb ub -> ClosedInterval lb ub ub 303 | ubInClosedInterval p = MkInterval p refl 304 | 305 | public export 306 | OpenInterval : (lb, ub : Int) -> (Int -> Type) 307 | OpenInterval = Interval False False 308 | 309 | ------------------------------------------------------------------------ 310 | -- Middle point 311 | 312 | ||| Provided that `LTE a b`, the computation of middle should not overflow 313 | public export 314 | middle : (a, b : Int) -> Int 315 | middle a b = a + ((b - a) `shiftR` fromNat 1) 316 | 317 | ||| Provided that `LT a b`, we can guarantee that `middle a b` is in [|a,b[|. 318 | export 319 | middleInInterval : {a, b : Int} -> LT a b -> Interval True False a b (middle a b) 320 | middleInInterval p = strictLT p $ MkInterval unsafeLTE (MkLT unsafeRefl) 321 | 322 | where 323 | 324 | ||| DO NOT re-export! 325 | unsafeLTE : LTE a (middle a b) 326 | unsafeLTE with (LTE.decide a (middle a b)) 327 | unsafeLTE | Yes p = p 328 | unsafeLTE | No np = assert_total $ idris_crash "Error: invalid call to unsafeLTE" 329 | -------------------------------------------------------------------------------- /src/Data/Order.idr: -------------------------------------------------------------------------------- 1 | module Data.Order 2 | 3 | %default total 4 | 5 | public export 6 | data Trichotomous : (lt, eq, gt : a -> a -> Type) -> (a -> a -> Type) where 7 | MkLT : {0 lt, eq, gt : a -> a -> Type} -> 8 | lt v w -> Not (eq v w) -> Not (gt v w) -> Trichotomous lt eq gt v w 9 | MkEQ : {0 lt, eq, gt : a -> a -> Type} -> 10 | Not (lt v w) -> eq v w -> Not (gt v w) -> Trichotomous lt eq gt v w 11 | MkGT : {0 lt, eq, gt : a -> a -> Type} -> 12 | Not (lt v w) -> Not (eq v w) -> gt v w -> Trichotomous lt eq gt v w 13 | -------------------------------------------------------------------------------- /src/Data/Order/Extended.idr: -------------------------------------------------------------------------------- 1 | module Data.Order.Extended 2 | 3 | import Data.Order 4 | 5 | %default total 6 | 7 | public export 8 | data Extended a = MInf | PInf | Lift a 9 | 10 | namespace LT 11 | 12 | public export 13 | data ExtendedLT : (a -> a -> Type) -> (Extended a -> Extended a -> Type) where 14 | MInfPInf : ExtendedLT lt MInf PInf 15 | MInfLift : ExtendedLT lt MInf (Lift v) 16 | LiftLift : {0 v, w : a} -> lt v w -> ExtendedLT lt (Lift v) (Lift w) 17 | LiftPInf : ExtendedLT lt (Lift v) PInf 18 | 19 | export 20 | LiftInversion : ExtendedLT lt (Lift x) (Lift y) -> lt x y 21 | LiftInversion (LiftLift p) = p 22 | 23 | export 24 | trans : (tr : {x, y, z : a} -> lt x y -> lt y z -> lt x z) -> 25 | {x, y, z : Extended a} -> ExtendedLT lt x y -> ExtendedLT lt y z -> ExtendedLT lt x z 26 | trans tr MInfLift (LiftLift q) = MInfLift 27 | trans tr MInfLift LiftPInf = MInfPInf 28 | trans tr (LiftLift p) (LiftLift q) = LiftLift (tr p q) 29 | trans tr (LiftLift p) LiftPInf = LiftPInf 30 | 31 | public export 32 | ExtendedGT : (a -> a -> Type) -> (Extended a -> Extended a -> Type) 33 | ExtendedGT gt = flip (ExtendedLT (flip gt)) 34 | 35 | export Uninhabited (ExtendedLT lt MInf MInf) where uninhabited p impossible 36 | export Uninhabited (ExtendedLT lt (Lift x) MInf) where uninhabited p impossible 37 | export Uninhabited (ExtendedLT lt PInf MInf) where uninhabited p impossible 38 | export Uninhabited (ExtendedLT lt PInf (Lift y)) where uninhabited p impossible 39 | export Uninhabited (ExtendedLT lt PInf PInf) where uninhabited p impossible 40 | 41 | namespace EQ 42 | 43 | public export 44 | data ExtendedEQ : (a -> a -> Type) -> (Extended a -> Extended a -> Type) where 45 | MInfMInf : ExtendedEQ eq MInf MInf 46 | LiftLift : {0 v, w : a} -> eq v w -> ExtendedEQ eq (Lift v) (Lift w) 47 | PInfPInf : ExtendedEQ eq PInf PInf 48 | 49 | export 50 | LiftInversion : ExtendedEQ eq (Lift x) (Lift y) -> eq x y 51 | LiftInversion (LiftLift p) = p 52 | 53 | export Uninhabited (ExtendedEQ lt MInf (Lift y)) where uninhabited p impossible 54 | export Uninhabited (ExtendedEQ lt MInf PInf) where uninhabited p impossible 55 | export Uninhabited (ExtendedEQ lt (Lift x) MInf) where uninhabited p impossible 56 | export Uninhabited (ExtendedEQ lt (Lift x) PInf) where uninhabited p impossible 57 | export Uninhabited (ExtendedEQ lt PInf (Lift y)) where uninhabited p impossible 58 | export Uninhabited (ExtendedEQ lt PInf MInf) where uninhabited p impossible 59 | 60 | 61 | export 62 | trichotomous : ((x, y : a) -> Trichotomous lt eq gt x y) -> 63 | ((x, y : Extended a) -> Trichotomous (ExtendedLT lt) (ExtendedEQ eq) (ExtendedGT gt) x y) 64 | trichotomous tri MInf MInf = MkEQ absurd MInfMInf absurd 65 | trichotomous tri MInf (Lift y) = MkLT MInfLift absurd absurd 66 | trichotomous tri MInf PInf = MkLT MInfPInf absurd absurd 67 | trichotomous tri (Lift x) MInf = MkGT absurd absurd MInfLift 68 | trichotomous tri (Lift x) PInf = MkLT LiftPInf absurd absurd 69 | trichotomous tri PInf MInf = MkGT absurd absurd MInfPInf 70 | trichotomous tri PInf (Lift y) = MkGT absurd absurd LiftPInf 71 | trichotomous tri PInf PInf = MkEQ absurd PInfPInf absurd 72 | trichotomous tri (Lift x) (Lift y) with (tri x y) 73 | trichotomous tri (Lift x) (Lift y) | MkLT p q r 74 | = MkLT (LiftLift p) (q . EQ.LiftInversion) (r . LT.LiftInversion) 75 | trichotomous tri (Lift x) (Lift y) | MkEQ p q r 76 | = MkEQ (p . LT.LiftInversion) (LiftLift q) (r . LT.LiftInversion) 77 | trichotomous tri (Lift x) (Lift y) | MkGT p q r 78 | = MkGT (p . LT.LiftInversion) (q . EQ.LiftInversion) (LiftLift r) 79 | -------------------------------------------------------------------------------- /src/binary-search.ipkg: -------------------------------------------------------------------------------- 1 | package binary-search 2 | -- version = 3 | authors = "Guillaume ALLAIS " 4 | -- maintainers = 5 | -- license = 6 | -- brief = 7 | -- readme = 8 | -- homepage = 9 | -- sourceloc = 10 | -- bugtracker = 11 | 12 | -- packages to add to search path 13 | depends = contrib 14 | 15 | -- modules to install 16 | modules = BT.Safe, 17 | Data.Array.ReadOnly, 18 | Data.Int.Order, 19 | Data.Order, 20 | Data.Order.Extended 21 | 22 | -- main file (i.e. file to load at REPL) 23 | -- main = 24 | 25 | -- name of executable 26 | -- executable = 27 | -- opts = 28 | -- sourcedir = 29 | -- builddir = 30 | -- outputdir = 31 | 32 | -- script to run before building 33 | -- prebuild = 34 | 35 | -- script to run after building 36 | -- postbuild = 37 | 38 | -- script to run after building, before installing 39 | -- preinstall = 40 | 41 | -- script to run after installing 42 | -- postinstall = 43 | 44 | -- script to run before cleaning 45 | -- preclean = 46 | 47 | -- script to run after cleaning 48 | -- postclean = 49 | --------------------------------------------------------------------------------