├── .github └── FUNDING.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── fpy.png ├── fpy ├── __init__.py ├── composable │ ├── __init__.py │ ├── collections.py │ ├── composable.py │ ├── function.py │ └── transparent.py ├── control │ ├── __init__.py │ ├── applicative.py │ ├── functor.py │ ├── monad.py │ └── natural_transform.py ├── data │ ├── __init__.py │ ├── cont.py │ ├── either.py │ ├── forgetful.py │ ├── function.py │ ├── maybe.py │ └── state.py ├── debug │ ├── __init__.py │ └── debug.py ├── experimental │ ├── __init__.py │ ├── case.py │ ├── do.py │ └── pattern │ │ ├── __init__.py │ │ └── core.py ├── parsec │ ├── __init__.py │ └── parsec.py ├── tests │ ├── __init__.py │ ├── test_composable.py │ ├── test_cont.py │ ├── test_ctx_do.py │ ├── test_do.py │ ├── test_either.py │ ├── test_function.py │ ├── test_maybe.py │ ├── test_parsec.py │ ├── test_pat.py │ └── test_state.py └── utils │ ├── __init__.py │ └── placeholder.py └── setup.py /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [Z-Shang] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | .venv 3 | *.egg-info 4 | dist 5 | build 6 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 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 | ![FPy](https://github.com/Z-Shang/fpy/blob/c60c60d16127723fcc4e30683de1ba39190f4467/fpy.png) 2 | 3 | [![version_badge](https://img.shields.io/pypi/v/fppy.svg)](https://pypi.org/project/fppy/0.0.18.post4/) 4 | # Functional Python 5 | 6 | For better computation composing in Python 7 | 8 | ## Goals 9 | * To bring the ability of composing computations in the functional way 10 | * Make my life easier 11 | 12 | ## No Goals 13 | * Exact clone of Haskell 14 | * Blazing fast / super efficient 15 | 16 | ## Python is Already Amazing, Why Bother? 17 | * Because I can 18 | * Python may be amazing in some field, but sucks from the functional perspective 19 | 20 | ## Python Sucks, Why Bother? 21 | * Because I can 22 | * Python is still used in my work place 23 | 24 | ## Install 25 | With pip: 26 | > pip install fppy 27 | 28 | ## Control: 29 | ### Functor `fpy.control.functor` 30 | Given Functors `f`, `g`: 31 | * `__fmap__ :: f a -> (a -> b) -> f b` 32 | * `__ntrans__ :: f a -> (f a ~> g b) -> g b` 33 | 34 | #### Operators: 35 | * `|` = `__fmap__` 36 | * `&` = `__ntrans__` 37 | 38 | #### Functions: 39 | * `fmap` = `__fmap__` 40 | 41 | ### NTrans (Natrual Transform) `fpy.control.natural_transform` 42 | Given Functors `f`, `g`: 43 | * `__trans__ :: f a ~> g b` 44 | 45 | ### Applicative : Functor `fpy.control.applicative` 46 | No new trait comparing to functor, `liftA2` is defined using `fmap` 47 | 48 | ### Monad : Applicative `fpy.control.monad` 49 | Given Monad `m`: 50 | * `__bind__ :: m a -> (a -> m b) -> m b` 51 | 52 | #### Operators: 53 | * `>>` = `__bind__` 54 | 55 | #### Do Notation: 56 | * `@do(Monad)` enables do notation in the decorated function, where the explicit `return` statement will be treated as `ret` from the given `Monad` type, if no `return` statement is given, the last element on the stack will be returned. 57 | * `name <- computation` binds the computation to the following block, calling the `__bind__` method of the monad object returned from `computation` with the name `name`. 58 | * `(name1, name2, ..., namen) <- computation` works in the similar way as the single name binding, this applys the binding function to the tuple contained within the monad object instead of calling the function directly. 59 | * `name1, name2, ..., namen <- computation` same as above 60 | 61 | ## Data 62 | ### Maybe : Monad `fpy.data.maybe` 63 | #### Types: 64 | * `Maybe[T]` 65 | * `Just[T] : Maybe[T]` 66 | * `Nothing[T] : Maybe[T]` 67 | #### Functions: 68 | * `isJust :: Maybe[T] -> bool` 69 | * `isNothing :: Maybe[T] -> bool` 70 | * `fromJust :: Maybe[T] -> T` 71 | * `fromMaybe :: T -> Maybe[T] -> T` 72 | * `maybe :: S -> (T -> S) -> Maybe[T] -> S` 73 | * `mapMaybe :: (T -> Maybe[S]) -> List[T] -> List[S]` 74 | 75 | ### Either : Monad `fpy.data.either` 76 | #### Types: 77 | * `Either[T]` 78 | * `Left[T] : Either[T]` 79 | * `Right[T] : Either[T]` 80 | 81 | ### Forgetful : Monad (Forgetful Functor) `fpy.data.forgetful` 82 | #### Types: 83 | * `Under[T]` 84 | `Under` similar to Haskell's `Identity` monad 85 | 86 | ### Cont : Monad `fpy.data.cont` 87 | #### Types: 88 | * `Cont[T, R]` 89 | 90 | #### Functions: 91 | * `cont :: (A -> B) -> Cont[A, B]` 92 | * `runCont :: Cout[B, C] -> C` 93 | 94 | #### Functions: 95 | Given functor `f`: 96 | `forget: NTrans[F, B, Under, T] :: f b ~> Under[T]` 97 | 98 | 99 | ### Utility Functions `fpy.data.function` 100 | * `id_ :: T -> T` 101 | * `const :: T -> A -> T` 102 | * `flip :: (B -> A -> T) -> A -> B -> T` 103 | * `fix :: (A -> A) -> A` 104 | * `on :: (B -> B -> T) -> (A -> B) -> A -> A -> T` 105 | 106 | #### Slightly Dependent Utilities 107 | ``` 108 | -- not so well typed 109 | 110 | NArg :: Nat -> Type 111 | NArg (S Z) = A 112 | NArg (S n) = A -> (NArg n) 113 | 114 | NTpl :: (n:Nat) -> (NArg n) -> Type 115 | NTpl (S Z) A =( A,) 116 | NTpl (S n) (A -> NArg n) = cons A (NTpl n (NArg n)) 117 | ``` 118 | 119 | * `constN :: (n:Nat) -> A -> (NArg n) -> A` 120 | * `uncurryN :: (n:Nat) -> args:(NArg n) -> A -> ((NTpl n args) -> A)` 121 | 122 | ## Composable 123 | ### Composable `fpy.composable.composable` 124 | * `__compose__` 125 | #### Operators: 126 | * `^` = `__compose__` 127 | 128 | ### Transparent `fpy.composable.transparent` 129 | * `__underlying__` 130 | Delegate an attribute access to an underlying object 131 | 132 | ### Function `fpy.composable.function` 133 | #### Types: 134 | * `func : Composable` 135 | * `SignatureMismatchError` 136 | * `NotEnoughArgsError` 137 | 138 | ### Collections `fpy.composable.collections` 139 | #### Types: 140 | * `Seq : func` 141 | * `Map : func` 142 | 143 | #### Functions: 144 | * `transN(n, f, it) := it[n] = f(it[n])` 145 | * `getN(n, it) := it[n]` 146 | * `setN(n, v, it) := it[n] = v` 147 | * `eqN(n, it, x) := it[n] == x` 148 | * `mapN(n, fn, lsts) := map(fn, zip(lst1, lst2 ... lstn))` 149 | * `of_(v1 ... vn) := _ in (v1 ... vn)` 150 | * `is_(t) := isinstance(_, t)` 151 | * `and_(a, b) := a(_) and b(_)` 152 | * `or_(a, b) := a(_) or b(_)` 153 | * `to(dst, src) := dst(src)` 154 | * `apply(fn) := fn(*a, **k)` 155 | * `fwd_ = Under.ret` 156 | 157 | #### Predefined Vars: 158 | * `trans0` 159 | * `trans1` 160 | * `get0` 161 | * `get1` 162 | * `set0` 163 | * `set1` 164 | * `eq0` 165 | * `eq1` 166 | * `mp1` 167 | * `mp2` 168 | 169 | ## Parsec 170 | ### Parsec `fpy.parsec.parsec` 171 | #### Types: 172 | * `parser[S, T] :: [S] -> Either [S] ([T] * [S])` 173 | 174 | #### Operators: 175 | * `*` = `parser.timeN` 176 | * `+` = `parser.concat` 177 | * `|` = `parser.choice` 178 | * `>>` = `parser.parseR` 179 | * `<<` = `parser.parseL` 180 | 181 | #### Functions: 182 | * `one :: (S -> bool) -> parser[S, S]` 183 | * `neg :: (S -> bool) -> parser[S, S]` 184 | * `just_nothing :: parser[S, T]` 185 | * `pmaybe :: parser[S, T] -> parser[S, T]` 186 | * `many :: parser[S, T] -> parser[S, T]` 187 | * `many1 :: parser[S, T] -> parser[S, T]` 188 | * `ptrans :: parser[S, T] -> (T -> Y) -> parser[S, Y]` 189 | * `peek :: parser[S, T] -> parser[S, T]` 190 | * `skip :: parser[S, T] -> parser[S, T]` 191 | * `pseq :: [S] -> parser[S, T]` 192 | * `inv :: parser[S, T] -> parser[S, T]` 193 | 194 | ## Dependencies 195 | * [bytecode](https://github.com/MatthieuDartiailh/bytecode) 196 | 197 | ## License 198 | GPL3+ 199 | -------------------------------------------------------------------------------- /fpy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Z-Shang/fpy/16463b895dcde8d1b9da7048e795d5084b6e138c/fpy.png -------------------------------------------------------------------------------- /fpy/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Z-Shang/fpy/16463b895dcde8d1b9da7048e795d5084b6e138c/fpy/__init__.py -------------------------------------------------------------------------------- /fpy/composable/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Z-Shang/fpy/16463b895dcde8d1b9da7048e795d5084b6e138c/fpy/composable/__init__.py -------------------------------------------------------------------------------- /fpy/composable/collections.py: -------------------------------------------------------------------------------- 1 | from fpy.composable.function import func, NotEnoughArgsError 2 | from fpy.data.forgetful import Under 3 | from fpy.data.function import const 4 | 5 | import collections.abc as cabc 6 | 7 | 8 | def get_item(c, *args, **kwargs): 9 | return c.__getitem__(*args, **kwargs) 10 | 11 | 12 | class Seq(func): 13 | def __init__(self, l): 14 | assert isinstance(l, cabc.Sequence), f"{l} is not a sequence" 15 | self._l = l 16 | super().__init__(get_item, l) 17 | 18 | def __getattr__(self, *args, **kwargs): 19 | return self._l.__getattribute__(*args, **kwargs) 20 | 21 | def __getitem__(self, *args, **kwargs): 22 | return self._l.__getitem__(*args, **kwargs) 23 | 24 | def __str__(self): 25 | return f"#Seq{str(self._l)}" 26 | 27 | def __repr__(self): 28 | return f"#Seq{repr(self._l)}" 29 | 30 | def split(self, pred): 31 | a = [] 32 | b = [] 33 | for v in self._l: 34 | if pred(v): 35 | a.append(v) 36 | else: 37 | b.append(v) 38 | return a, b 39 | 40 | def filter(self, pred): 41 | return get0(self.split(pred)) 42 | 43 | 44 | class Map(func): 45 | def __init__(self, m): 46 | assert isinstance(m, cabc.Mapping), f"{m} is not a map" 47 | self._m = m 48 | super().__init__(get_item, m) 49 | 50 | def __getattr__(self, *args, **kwargs): 51 | return self._m.__getattribute__(*args, **kwargs) 52 | 53 | def __getitem__(self, *args, **kwargs): 54 | return self._m.__getitem__(*args, **kwargs) 55 | 56 | def __str__(self): 57 | return f"#Map{str(self._m)}" 58 | 59 | def __repr__(self): 60 | return f"#Map{repr(self._m)}" 61 | 62 | def split(self, pred): 63 | a = {} 64 | b = {} 65 | for k, v in self._m.items(): 66 | if pred(k): 67 | a[k] = v 68 | else: 69 | b[k] = v 70 | return a, b 71 | 72 | def filter(self, pred): 73 | return get0(self.split(pred)) 74 | 75 | 76 | @func 77 | def transN(n, fn, it): 78 | return type(it)((fn(v) if _i == n else v for _i, v in enumerate(it))) 79 | 80 | 81 | trans0 = transN(0) 82 | trans1 = transN(1) 83 | 84 | 85 | @func 86 | def setN(n, v, it): 87 | return transN(n, const(v), it) 88 | 89 | 90 | set0 = setN(0) 91 | set1 = setN(1) 92 | 93 | 94 | @func 95 | def getN(n, x): 96 | return x[n] 97 | 98 | 99 | get0 = getN(0) 100 | get1 = getN(1) 101 | 102 | def not_(pred): 103 | return func(lambda x: not pred(x)) 104 | 105 | def of_(*it): 106 | return func(lambda x: x in it) 107 | 108 | 109 | def is_(ty): 110 | return func(lambda x: isinstance(x, ty)) 111 | 112 | 113 | def and_(a, b): 114 | @func 115 | def __and(*args, **kwargs): 116 | _a = a(*args, **kwargs) 117 | if _a: 118 | return b(*args, **kwargs) 119 | return _a 120 | 121 | return __and 122 | 123 | 124 | def or_(a, b): 125 | @func 126 | def __or(*args, **kwargs): 127 | _a = a(*args, **kwargs) 128 | if not _a: 129 | return b(*args, **kwargs) 130 | return _a 131 | 132 | return __or 133 | 134 | 135 | @func 136 | def to(dst, src): 137 | return dst(src) 138 | 139 | 140 | def apply(fn): 141 | @func 142 | def __apply(_a=None, _k=None): 143 | a = _a if _a is not None else () 144 | k = _k if _k is not None else {} 145 | return fn(*a, **k) 146 | 147 | return __apply 148 | 149 | 150 | @func 151 | def mapN(n, fn, *lsts): 152 | if len(lsts) < n: 153 | raise NotEnoughArgsError(n, len(lsts)) 154 | ap = apply(fn) 155 | return [ap(row) for row in zip(*lsts)] 156 | 157 | 158 | mp1 = mapN(1) 159 | mp2 = mapN(2) 160 | 161 | 162 | @func 163 | def eqN(n, it, x): 164 | return x == it[n] 165 | 166 | 167 | eq0 = eqN(0) 168 | eq1 = eqN(1) 169 | 170 | fwd_ = Under.ret 171 | 172 | def seq2map(*keys): 173 | @func 174 | def __seq2map(*vals): 175 | if len(vals) < len(keys): 176 | raise NotEnoughArgsError(len(keys), len(vals)) 177 | return dict(zip(keys, vals)) 178 | 179 | return __seq2map 180 | -------------------------------------------------------------------------------- /fpy/composable/composable.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod, abstractclassmethod 2 | 3 | 4 | class Composable(metaclass=ABCMeta): 5 | @abstractmethod 6 | def __compose__(self, other): 7 | raise NotImplementedError 8 | 9 | def __xor__(self, other): 10 | return self.__compose__(other) 11 | -------------------------------------------------------------------------------- /fpy/composable/function.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import inspect 4 | import collections.abc as cabc 5 | 6 | from fpy.composable.composable import Composable 7 | from fpy.composable.transparent import Transparent 8 | 9 | from typing import Callable, TypeVar, Generic, Union, Any 10 | 11 | import sys 12 | import traceback 13 | 14 | class SignatureMismatchError(Exception): 15 | def __init__(self, e): 16 | self.e = e 17 | 18 | 19 | class NotEnoughArgsError(Exception): 20 | def __init__(self, expect, got): 21 | self.expect = expect 22 | self.got = got 23 | 24 | R = TypeVar("R") 25 | 26 | class func(Composable, Transparent, Generic[R], Callable[[Any], R]): 27 | fn: Callable[[Any], R] = None 28 | 29 | def __init__(self, f, *args, **kwargs): 30 | if isinstance(f, func): 31 | self.fn = f.fn 32 | self.args = (*f.args, *args) 33 | self.kwargs = {**f.kwargs, **kwargs} 34 | self.sig = f.sig 35 | elif isinstance(f, cabc.Callable): 36 | self.fn = f 37 | self.args = args 38 | self.kwargs = kwargs 39 | self.sig = inspect.signature(f) 40 | else: 41 | raise TypeError(f"{f} is not callable") 42 | 43 | def __underlying__(self): 44 | return self.fn 45 | 46 | def __repr__(self): 47 | return repr(self.fn) 48 | 49 | def __call__(self, *args, **kwargs) -> Union[R, func[R]]: 50 | _args = (*self.args, *args) 51 | _kwargs = {**self.kwargs, **kwargs} 52 | try: 53 | self.sig.bind(*_args, **_kwargs) 54 | return self.fn(*_args, **_kwargs) 55 | except TypeError as e: 56 | # print(f"TypeError: {e}", file=sys.stderr) 57 | # tb = sys.exc_info()[2] 58 | # print(f"{tb.tb_frame.f_code.co_filename = }, {tb.tb_lineno = }") 59 | # traceback.print_tb(tb) 60 | try: 61 | self.sig.bind_partial(*_args, **_kwargs) 62 | return func(self, *args, **kwargs) 63 | except TypeError as e: 64 | raise SignatureMismatchError(e) 65 | except NotEnoughArgsError: 66 | return func(self, *args, **kwargs) 67 | 68 | def __compose__(self, other): 69 | if isinstance(other, func): 70 | return self.__class__(lambda *args, **kwargs: other(self(*args, **kwargs))) 71 | if isinstance(other, cabc.Callable): 72 | fn = func(other) 73 | return self.__class__(lambda *args, **kwargs: fn(self(*args, **kwargs))) 74 | raise TypeError(f"Cannot compose function with {type(other)}") 75 | -------------------------------------------------------------------------------- /fpy/composable/transparent.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod, abstractclassmethod 2 | 3 | 4 | class Transparent(metaclass=ABCMeta): 5 | @abstractmethod 6 | def __underlying__(self): 7 | raise NotImplementedError 8 | 9 | def __getattr__(self, name): 10 | try: 11 | return self.__getattribute__(name) 12 | except AttributeError: 13 | return getattr(self.__underlying__(), name) 14 | -------------------------------------------------------------------------------- /fpy/control/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Z-Shang/fpy/16463b895dcde8d1b9da7048e795d5084b6e138c/fpy/control/__init__.py -------------------------------------------------------------------------------- /fpy/control/applicative.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from abc import ABCMeta, abstractmethod, abstractclassmethod 4 | from fpy.control.functor import _Functor 5 | 6 | from dataclasses import dataclass 7 | from typing import TypeVar, Generic, Callable 8 | 9 | T = TypeVar("T") 10 | S = TypeVar("S") 11 | 12 | 13 | class _Applicative(_Functor[T], Generic[T]): 14 | @classmethod 15 | def pure(cls, val): 16 | return cls(val) 17 | 18 | @classmethod 19 | def liftA2(cls, f, a, b): 20 | return cls.fmap(cls.fmap(f, a), b) 21 | 22 | 23 | @dataclass 24 | class Applicative(_Applicative[T], Generic[T]): 25 | val: T 26 | 27 | def __fmap__(self, f: Callable[[T], S]) -> _Applicative[S]: 28 | return type(self)(f(self.val)) 29 | -------------------------------------------------------------------------------- /fpy/control/functor.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from abc import ABCMeta, abstractmethod 4 | from dataclasses import dataclass 5 | from typing import TypeVar, Generic, Callable 6 | 7 | from fpy.control.natural_transform import _NTrans 8 | from fpy.composable.function import func 9 | 10 | T = TypeVar("T") 11 | F = TypeVar("F") 12 | G = TypeVar("G") 13 | A = TypeVar("A") 14 | B = TypeVar("B") 15 | 16 | 17 | class _Functor(Generic[T], metaclass=ABCMeta): 18 | @classmethod 19 | def fmap(cls, f: Callable[[A], B], a: _Functor[A]) -> _Functor[B]: 20 | assert isinstance(a, cls) 21 | return a.__fmap__(f) 22 | 23 | def __fmap__(self, f: Callable[[T], B]) -> _Functor[B]: 24 | raise NotImplementedError 25 | 26 | def __ntrans__(self, t: _NTrans[_Functor, T, G, B]) -> G[B]: 27 | """ 28 | Natrual transformation: 29 | __ntrans__ :: f a -> (f a -> g b) -> g b 30 | """ 31 | raise NotImplementedError 32 | 33 | def __and__(self, t: _NTrans[_Functor, T, G, B]) -> G[B]: 34 | return t.__trans__(self) 35 | 36 | def __or__(self, f): 37 | return self.__fmap__(f) 38 | 39 | 40 | @dataclass 41 | class Functor(_Functor[T], Generic[T]): 42 | val: T 43 | 44 | def __fmap__(self, f: Callable[[T], B]) -> _Functor[B]: 45 | return type(self)(f(self.val)) 46 | 47 | def __ntrans__(self, t: Callable[[T], G[B]]) -> G[B]: 48 | return t(self.val) 49 | 50 | @func 51 | def fmap(o: F[A], f: Callable[[A], B]) -> F[B]: 52 | return o.__fmap__(f) 53 | -------------------------------------------------------------------------------- /fpy/control/monad.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod 2 | 3 | from fpy.control.applicative import _Applicative 4 | from typing import TypeVar, Generic, Callable 5 | 6 | 7 | T = TypeVar("T") 8 | R = TypeVar("R") 9 | 10 | 11 | class _Monad(_Applicative[T], Generic[T]): 12 | @classmethod 13 | def ret(cls, val): 14 | return cls(val) 15 | 16 | def __bind__(self, b): 17 | raise NotImplementedError 18 | 19 | def __rshift__(self, b): 20 | return self.__bind__(b) 21 | 22 | def __enter__(self): 23 | raise DoFail(self) 24 | 25 | def __exit__(self, et, ev, tb): 26 | pass 27 | 28 | 29 | class DoFail(Exception): 30 | def __init__(self, m): 31 | super() 32 | self.m = m 33 | 34 | def do(fn): 35 | def res(*args, **kwargs): 36 | try: 37 | return fn(*args, **kwargs) 38 | except DoFail as f: 39 | return f.m 40 | return res 41 | -------------------------------------------------------------------------------- /fpy/control/natural_transform.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from abc import ABCMeta, abstractmethod 4 | from dataclasses import dataclass 5 | from typing import TypeVar, Generic, Callable 6 | 7 | 8 | F = TypeVar("F") 9 | G = TypeVar("G") 10 | A = TypeVar("A") 11 | B = TypeVar("B") 12 | 13 | 14 | class _NTrans(Generic[F, A, G, B], metaclass=ABCMeta): 15 | @abstractmethod 16 | def __trans__(self, v: A) -> G[B]: 17 | raise NotImplementedError 18 | 19 | def __call__(self, v: A) -> G[B]: 20 | return self.__trans__(v) 21 | 22 | 23 | @dataclass 24 | class NTrans(_NTrans): 25 | f: Callable[[A], G[B]] 26 | 27 | def __trans__(self, v: F[A]) -> G[B]: 28 | assert hasattr(v, "__ntrans__") 29 | return v.__ntrans__(self.f) 30 | -------------------------------------------------------------------------------- /fpy/data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Z-Shang/fpy/16463b895dcde8d1b9da7048e795d5084b6e138c/fpy/data/__init__.py -------------------------------------------------------------------------------- /fpy/data/cont.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from fpy.control.monad import _Monad 4 | from fpy.composable.function import func, SignatureMismatchError 5 | 6 | import bytecode as bc 7 | 8 | from dataclasses import dataclass 9 | from typing import TypeVar, Generic, Callable 10 | 11 | import sys 12 | 13 | 14 | T = TypeVar("T") 15 | R = TypeVar("R") 16 | S = TypeVar("S") 17 | 18 | 19 | @dataclass 20 | class Cont(_Monad[R], Generic[T, R]): 21 | f: Callable[[T], R] 22 | 23 | def __init__(self, f): 24 | self.f = func(f) 25 | 26 | def __bind__(self, f): 27 | return self.__class__.ret(lambda k: self.f(lambda *a: f(*a).__run__(k))) 28 | 29 | def __ntrans__(self, t): 30 | return self.f(t) 31 | 32 | def __call__(self, *a, **k): 33 | try: 34 | res = self.f(*a, **k) 35 | if isinstance(res, func) and res.f is self.f: 36 | return Cont(res) 37 | return Cont(lambda k: k(res)) 38 | except SignatureMismatchError as e: 39 | raise e.e 40 | 41 | def __run__(self, k: Cont[[R], S]): 42 | return self.f(k) 43 | 44 | 45 | def runCont(c, k): 46 | return c.__run__(k) 47 | 48 | 49 | def to_cont(v): 50 | return Cont(lambda k: k(v)) 51 | 52 | 53 | def cont(f: Callable[[T], R]) -> Cont[T, R]: 54 | raw_bc = bc.Bytecode.from_code(f.__code__) 55 | 56 | print(raw_bc) 57 | res_bc = [] 58 | for inst in raw_bc: 59 | if not isinstance(inst, bc.Instr): 60 | res_bc.append(inst) 61 | continue 62 | if inst.name != "RETURN_VALUE": 63 | res_bc.append(inst) 64 | continue 65 | 66 | res_bc.append(bc.Instr("LOAD_CONST", to_cont, lineno=inst.lineno)) 67 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 68 | res_bc.append(bc.Instr("PUSH_NULL", lineno=inst.lineno)) 69 | res_bc.append(bc.Instr("SWAP", 3, lineno=inst.lineno)) 70 | res_bc.append(bc.Instr("PRECALL", 1)) 71 | res_bc.append(bc.Instr("CALL", 1)) 72 | else: 73 | res_bc.append(bc.Instr("ROT_TWO", lineno=inst.lineno)) 74 | res_bc.append(bc.Instr("CALL_FUNCTION", 1, lineno=inst.lineno)) 75 | res_bc.append(inst) 76 | print(res_bc) 77 | bc_obj = bc.Bytecode(res_bc) 78 | bc_obj.freevars = f.__code__.co_freevars 79 | bc_obj.cellvars = f.__code__.co_cellvars 80 | bc_obj.argcount = f.__code__.co_argcount 81 | bc_obj.name = f.__name__ 82 | f.__code__ = bc_obj.to_code() 83 | return func(f) 84 | -------------------------------------------------------------------------------- /fpy/data/either.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from fpy.composable.function import func 4 | from fpy.control.monad import _Monad 5 | from fpy.control.natural_transform import NTrans, _NTrans 6 | from abc import ABCMeta, abstractmethod, abstractclassmethod 7 | import collections.abc as cabc 8 | from dataclasses import dataclass 9 | from typing import TypeVar, Generic, Callable, List, Tuple 10 | 11 | 12 | T = TypeVar("T") 13 | R = TypeVar("R") 14 | L = TypeVar("L") 15 | G = TypeVar("G") 16 | 17 | 18 | class Either(_Monad, Generic[L, R]): 19 | @abstractmethod 20 | def __bool__(self): 21 | return NotImplemented 22 | 23 | def __bind__(self, b): 24 | raise NotImplementedError 25 | 26 | 27 | @dataclass 28 | class Left(Either[L, R]): 29 | v: L 30 | 31 | def __bool__(self): 32 | return False 33 | 34 | def __fmap__(self, f: Callable[[L], T]) -> Left[T]: 35 | return self 36 | 37 | def __bind__(self, _) -> Left[L, R]: 38 | return self 39 | 40 | def __ntrans__(self, t: _NTrans[Either, [L, R], G, T]) -> G[T]: 41 | return t(self.v) 42 | 43 | 44 | @dataclass 45 | class Right(Either[L, R]): 46 | v: R 47 | 48 | def __bool__(self): 49 | return True 50 | 51 | def __fmap__(self, f: Callable[[R], T]) -> Right[T]: 52 | return Right(f(self.v)) 53 | 54 | def __bind__(self, b: Callable[[R], Either[T, G]]) -> Either[T, G]: 55 | return b(self.v) 56 | 57 | def __ntrans__(self, t: _NTrans[Either, [L, R], G, T]) -> G[T]: 58 | return t(self.v) 59 | 60 | def __enter__(self): 61 | return self.v 62 | 63 | 64 | def isLeft(e: Either[L, R]) -> bool: 65 | return isinstance(e, Left) 66 | 67 | 68 | def isRight(e: Either[L, R]) -> bool: 69 | return isinstance(e, Right) 70 | 71 | 72 | def fromLeft(d: L, e: Either[L, R]) -> L: 73 | return d if not isLeft(e) else e.v 74 | 75 | 76 | def fromRight(d: R, e: Either[L, R]) -> R: 77 | return d if not isRight(e) else e.v 78 | 79 | 80 | @func 81 | def either(fl: Callable[[L], T], fr: Callable[[R], T], e: Either[L, R]) -> T: 82 | if isLeft(e): 83 | return fl(fromLeft(None, e)) 84 | return fr(fromRight(None, e)) 85 | 86 | 87 | def lefts(l: cabc.Sequence[Either[L, R]]) -> List[L]: 88 | return [fromLeft(None, v) for v in l if isLeft(v)] 89 | 90 | 91 | def rights(l: cabc.Sequence[Either[L, R]]) -> List[R]: 92 | return [fromRight(None, v) for v in l if isRight(v)] 93 | 94 | 95 | r2l: _NTrans[Right, T, Left, T] = NTrans(Left) 96 | l2r: _NTrans[Left, T, Right, T] = NTrans(Right) 97 | 98 | 99 | def partitionEithers(lst: cabc.Sequence[Either[L, R]]) -> Tuple[List[L], List[R]]: 100 | l = [] 101 | r = [] 102 | for e in lst: 103 | if isLeft(e): 104 | l.append(fromLeft(None, e)) 105 | else: 106 | r.append(fromRight(None, e)) 107 | return l, r 108 | -------------------------------------------------------------------------------- /fpy/data/forgetful.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from dataclasses import dataclass 4 | from typing import TypeVar, Generic, Callable 5 | 6 | from fpy.control.monad import _Monad 7 | from fpy.control.natural_transform import NTrans, _NTrans 8 | 9 | 10 | T = TypeVar("T") 11 | F = TypeVar("F") 12 | G = TypeVar("G") 13 | B = TypeVar("B") 14 | 15 | 16 | @dataclass 17 | class Under(_Monad, Generic[T]): 18 | v: T 19 | 20 | def under(self): 21 | return self.v 22 | 23 | def __fmap__(self, f: Callable[[T], B]) -> Under[B]: 24 | return Under(f(self.v)) 25 | 26 | def __ntrans__(self, t: Callable[[T], G[B]]) -> G[B]: 27 | return t(self.val) 28 | 29 | def __bind__(self, b: Callable[[T], B]) -> Under[B]: 30 | return self.__fmap__(b) 31 | 32 | 33 | forget: _NTrans[F, B, Under, T] = NTrans(Under) 34 | -------------------------------------------------------------------------------- /fpy/data/function.py: -------------------------------------------------------------------------------- 1 | from fpy.composable.function import func 2 | 3 | from typing import TypeVar, Callable, Any 4 | 5 | T = TypeVar("T") 6 | F = TypeVar("F") 7 | A = TypeVar("A") 8 | B = TypeVar("B") 9 | 10 | 11 | def id_(x: T) -> T: 12 | return x 13 | 14 | 15 | @func 16 | def const(x: T, _: Any) -> T: 17 | return x 18 | 19 | 20 | @func 21 | def flip(f: Callable[[B, A], T], a: A, b: B) -> T: 22 | return f(b, a) 23 | 24 | 25 | def fix(f: Callable) -> Callable: 26 | fn = func(f) 27 | return lambda *args: fn(fix(fn))(*args) 28 | 29 | 30 | @func 31 | def on(b: Callable[[B, B], T], u: Callable[[A], B], x: A, y: A) -> T: 32 | return b(u(x), u(y)) 33 | 34 | @func 35 | def constN(n: int, x): 36 | if n == 1: 37 | return const(x) 38 | return const(constN(n - 1, x)) 39 | 40 | def uncurryN(n: int, f): 41 | def _res(*args): 42 | if len(args) != n: 43 | raise TypeError(f"Uncurried function {f} expected {n} arguments but {len(args)} was given") 44 | part = f 45 | for i in range(n): 46 | part = part(args[i]) 47 | return part 48 | 49 | return _res 50 | -------------------------------------------------------------------------------- /fpy/data/maybe.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from fpy.control.monad import _Monad 4 | from fpy.control.natural_transform import _NTrans 5 | from abc import ABCMeta, abstractmethod, abstractclassmethod 6 | import collections.abc as cabc 7 | from typing import TypeVar, Generic, List, Callable 8 | from dataclasses import dataclass 9 | 10 | T = TypeVar("T") 11 | S = TypeVar("S") 12 | G = TypeVar("G") 13 | 14 | 15 | class Maybe(_Monad[T], Generic[T]): 16 | @abstractmethod 17 | def __bool__(self): 18 | raise NotImplementedError 19 | 20 | def __bind__(self, b): 21 | raise NotImplementedError 22 | 23 | 24 | @dataclass 25 | class Just(Maybe[T], Generic[T]): 26 | v: T 27 | 28 | def __bool__(self): 29 | return True 30 | 31 | def __fmap__(self, f: Callable[[T], S]) -> Just[S]: 32 | return Just(f(self.v)) 33 | 34 | def __ntrans__(self, t: _NTrans[Maybe, T, G, S]) -> G[S]: 35 | return t(self.v) 36 | 37 | def __bind__(self, b: Callable[[T], Maybe[S]]) -> Maybe[S]: 38 | return b(self.v) 39 | 40 | def __enter__(self): 41 | return self.v 42 | 43 | 44 | class Nothing(Maybe[T], Generic[T]): 45 | def __bool__(self): 46 | return False 47 | 48 | def __bind__(self, _: any) -> Nothing[T]: 49 | return self 50 | 51 | def __ntrans__(self, t: _NTrans[Maybe, T, G, S]) -> G[S]: 52 | return t(None) 53 | 54 | def isJust(m: Maybe[T]) -> bool: 55 | return isinstance(m, Just) 56 | 57 | 58 | def isNothing(m: Maybe[T]) -> bool: 59 | return isinstance(m, Nothing) 60 | 61 | 62 | def fromJust(m: Maybe[T]) -> T: 63 | assert isinstance(m, Just) 64 | return m.v 65 | 66 | 67 | def fromMaybe(d: T, m: Maybe[T]) -> T: 68 | return d if not isJust(m) else fromJust(m) 69 | 70 | 71 | def maybe(d: S, f: Callable[[T], S], m: Maybe[T]) -> S: 72 | return d if not isJust(m) else f(fromJust(m)) 73 | 74 | 75 | def mapMaybe(f: Callable[[T], Maybe[S]], l: cabc.Sequence[T]) -> List[S]: 76 | return [fromJust(v) for v in map(f, l) if isJust(v)] 77 | -------------------------------------------------------------------------------- /fpy/data/state.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from fpy.control.monad import _Monad 4 | from fpy.composable.function import func, SignatureMismatchError 5 | from fpy.composable.collections import get0, get1 6 | from fpy.data.function import id_, const 7 | 8 | import bytecode as bc 9 | 10 | from dataclasses import dataclass 11 | from typing import TypeVar, Generic, Callable, Tuple 12 | 13 | import sys 14 | 15 | T = TypeVar("T") 16 | R = TypeVar("R") 17 | S = TypeVar("S") 18 | 19 | @dataclass 20 | class State(_Monad[S], Generic[S, T]): 21 | comp : Callable[[S], Tuple[T, S]] 22 | 23 | @classmethod 24 | def ret(cls, v : T): 25 | def res(s : S) -> Tuple[T, S]: 26 | return v, s 27 | return cls(res) 28 | 29 | def __bind__(self, b : Callable[[T], State[S, R]]) -> State[S, R]: 30 | def res(s: S): 31 | _v, _s = runState(self, s) 32 | return runState(b(_v), _s) 33 | return State(res) 34 | 35 | def runState(c : State[S, T], s : S) -> Tuple[T, S]: 36 | return c.comp(s) 37 | 38 | def get() -> State[S, S]: 39 | return State(lambda s: (s, s)) 40 | 41 | def put(x: S) -> State[None, S]: 42 | return State(const((None, x))) 43 | 44 | def modify(f : Callable[[S], S]) -> State[S, None]: 45 | return get() >> (lambda x: put(f(x))) 46 | 47 | def gets(f : Callable[[S], T]) -> State[S, T]: 48 | return get() >> (lambda x: State.ret(f(x))) 49 | 50 | def evalState(comp : State[S, T], s : S) -> T: 51 | return get0(runState(comp, s)) 52 | 53 | def execState(comp : State[S, T], s : S) -> T: 54 | return get1(runState(comp, s)) 55 | -------------------------------------------------------------------------------- /fpy/debug/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Z-Shang/fpy/16463b895dcde8d1b9da7048e795d5084b6e138c/fpy/debug/__init__.py -------------------------------------------------------------------------------- /fpy/debug/debug.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from fpy.composable.function import func 4 | 5 | 6 | @func 7 | def trace(txt, val): 8 | print(txt, val, file=sys.stderr) 9 | return val 10 | 11 | 12 | def showio(fn): 13 | def res(*args, **kwargs): 14 | print(f"{fn.__name__} input: {args, kwargs}", file=sys.stderr) 15 | ret = fn(*args, **kwargs) 16 | print(f"{fn.__name__} output: {ret}", file=sys.stderr) 17 | return ret 18 | 19 | return res 20 | -------------------------------------------------------------------------------- /fpy/experimental/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Z-Shang/fpy/16463b895dcde8d1b9da7048e795d5084b6e138c/fpy/experimental/__init__.py -------------------------------------------------------------------------------- /fpy/experimental/case.py: -------------------------------------------------------------------------------- 1 | import bytecode as bc 2 | import fpy.experimental.pattern.core as pat_core 3 | 4 | from fpy.data.function import const 5 | from fpy.composable.collections import is_, and_, or_, get1, mp1, trans0, get0, to 6 | from fpy.composable.function import func 7 | from fpy.data.forgetful import forget 8 | from fpy.data.maybe import Just, Nothing, isJust, fromJust 9 | from fpy.data.either import either, fromRight 10 | from fpy.experimental.do import do 11 | from fpy.parsec.parsec import one, many, neg, skip, many1, ptrans, s2c 12 | from fpy.utils.placeholder import __ 13 | 14 | from fpy.debug.debug import trace 15 | 16 | from dataclasses import dataclass 17 | from typing import List 18 | 19 | import sys 20 | 21 | import dis 22 | 23 | isInstr = is_(bc.Instr) 24 | popTop = and_(isInstr, __.name == "POP_TOP") 25 | none = and_(isInstr, and_(__.name == "LOAD_CONST", __.arg == None)) 26 | ret = and_(isInstr, __.name == "RETURN_VALUE") 27 | ending = one(popTop) >> one(none) >> one(ret) 28 | mkConstMap = and_(isInstr, __.name == "BUILD_CONST_KEY_MAP") 29 | mkMap = and_(isInstr, __.name == "BUILD_MAP") 30 | isArg = and_(isInstr, __.name == "LOAD_FAST") 31 | isLoadGlobal = and_(isInstr, __.name == "LOAD_GLOBAL") 32 | isVarName = lambda x: x != "_" and x.startswith("_") 33 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 34 | isVar = and_(isLoadGlobal, __.arg ^ get1 ^ isVarName) 35 | callInst = one(and_(isInstr, __.name == "PRECALL")) >> one( 36 | and_(isInstr, __.name == "CALL") 37 | ) 38 | isWildcard = and_(isLoadGlobal, __.arg ^ get1 == "_") 39 | else: 40 | isWildcard = and_(isLoadGlobal, __.arg == "_") 41 | isVar = and_(isLoadGlobal, __.arg ^ isVarName) 42 | callInst = one(and_(isInstr, __.name == "CALL_FUNCTION")) 43 | 44 | storeFast = and_(isInstr, __.name == "STORE_FAST") 45 | unpack = and_(isInstr, __.name == "UNPACK_SEQUENCE") 46 | 47 | isVarargFn = lambda fn: 1 == ((fn.__code__.co_flags >> 2) & 1) 48 | 49 | rightToMaybe = either(const(Nothing()), Just) 50 | 51 | @dataclass 52 | class CaseHead: 53 | args: List[str] 54 | 55 | 56 | @dataclass 57 | class CaseBody: 58 | insts: List[bc.Instr] 59 | 60 | 61 | @dataclass 62 | class StoreName: 63 | instrs: List[bc.Instr] 64 | 65 | 66 | @dataclass 67 | class Case: 68 | head: CaseHead 69 | body: CaseBody 70 | store: StoreName 71 | 72 | 73 | def exprToLambda(b, place, filename, args, fv, v=None): 74 | varMap = {arg: pat_core._fresh(arg) for arg in args} 75 | mod_b = [] 76 | free_vars = [] 77 | # print(f"{b = }") 78 | for instr in b: 79 | if isArg(instr): 80 | name = instr.arg 81 | if name in varMap: 82 | instr.arg = varMap[name] 83 | else: 84 | instr = bc.Instr("LOAD_DEREF", bc.FreeVar(name)) 85 | free_vars.append(name) 86 | if isVar(instr): 87 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 88 | name = instr.arg[1] 89 | else: 90 | name = instr.arg 91 | assert name in v, f"Variable: {name} is not bound" 92 | instr = bc.Instr("LOAD_FAST", varMap[v[name]]) 93 | if isLoadGlobal(instr): 94 | name = instr.arg[1] 95 | if name in varMap: 96 | instr = bc.Instr("LOAD_FAST", varMap[name]) 97 | mod_b.append(instr) 98 | mod_b.append(bc.Instr("RETURN_VALUE")) 99 | if free_vars and sys.version_info.major == 3 and sys.version_info.minor >= 11: 100 | mod_b.insert(0, bc.Instr("COPY_FREE_VARS", len(free_vars))) 101 | # print(f"{mod_b = }") 102 | lm = bc.Bytecode(mod_b) 103 | lm.freevars.extend(fv) 104 | lm.freevars.extend(free_vars) 105 | lm.argcount = len(varMap) 106 | lm.argnames.extend(list(varMap.values())) 107 | lm.name = pat_core._fresh(place, "exprlambda") 108 | lm.filename = filename 109 | lm.flags = lm.flags | 16 110 | lm.update_flags() 111 | co = lm.to_code() 112 | # print("=" * 20) 113 | # dis.dis(co) 114 | # dis.show_code(co) 115 | # print("=" * 20) 116 | return [ 117 | *[bc.Instr("LOAD_CLOSURE", bc.CellVar(f)) for f in free_vars], 118 | *([bc.Instr("BUILD_TUPLE", len(free_vars))] if free_vars else []), 119 | bc.Instr("LOAD_CONST", co), 120 | *([] if sys.version_info.major == 3 and sys.version_info.minor >= 11 else [bc.Instr("LOAD_CONST", lm.name)]), 121 | bc.Instr("MAKE_FUNCTION", 0x08 if free_vars else 0), 122 | ], free_vars 123 | 124 | 125 | def generateDefault(place, filename, args): 126 | varMap = {arg: pat_core._fresh(arg) for arg in args} 127 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 128 | lm = bc.Bytecode( 129 | [ 130 | bc.Instr("PUSH_NULL"), 131 | bc.Instr("LOAD_CONST", pat_core.NonExhaustivePatternError), 132 | ] 133 | ) 134 | else: 135 | lm = bc.Bytecode([bc.Instr("LOAD_CONST", pat_core.NonExhaustivePatternError)]) 136 | lm.append(bc.Instr("LOAD_CONST", f"Non Exhaustive Pattern Matching: {place}")) 137 | for k, v in varMap.items(): 138 | lm.append(bc.Instr("LOAD_CONST", f"\n{k}: ")) 139 | lm.append(bc.Instr("LOAD_FAST", v)) 140 | lm.append(bc.Instr("FORMAT_VALUE", 0x02)) 141 | lm.append(bc.Instr("BUILD_STRING", 1 + 2 * len(varMap))) 142 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 143 | lm.append(bc.Instr("PRECALL", 1)) 144 | lm.append(bc.Instr("CALL", 1)) 145 | else: 146 | lm.append(bc.Instr("CALL_FUNCTION", 1)) 147 | lm.append(bc.Instr("RAISE_VARARGS", 1)) 148 | lm.argcount = len(varMap) 149 | lm.argnames.extend(list(varMap.values())) 150 | lm.name = pat_core._fresh(place, "defaultcase") 151 | lm.filename = filename 152 | lm.flags = lm.flags | 16 153 | lm.update_flags() 154 | co = lm.to_code() 155 | return [ 156 | bc.Instr("LOAD_CONST", co), 157 | *([] if sys.version_info.major == 3 and sys.version_info.minor >= 11 else [bc.Instr("LOAD_CONST", lm.name)]), 158 | bc.Instr("MAKE_FUNCTION", 0), 159 | ] 160 | 161 | 162 | def partitionInst(insts, n): 163 | if not insts: 164 | return [], [] 165 | if n == 0: 166 | return [], insts 167 | head = insts[-1] 168 | # print(f"{head = }") 169 | # print(f"{n = }") 170 | pre, post = head.pre_and_post_stack_effect() 171 | # print(f"{pre = }") 172 | # print(f"{post= }") 173 | if pre > 0: 174 | if pre == n: 175 | return [head], insts[:-1] 176 | if pre < n: 177 | nxt, rst = partitionInst(insts[:-1], n - pre) 178 | return nxt + [head], rst 179 | if pre == 0: 180 | nxt, rst = partitionInst(insts[:-1], n - post) 181 | return nxt + [head], rst 182 | pre = abs(pre) 183 | nxt, rst = partitionInst(insts[:-1], pre) 184 | if post < n: 185 | head = nxt + [head] 186 | nxt, rst = partitionInst(rst, n - post) 187 | return nxt + head, rst 188 | # if post == n: 189 | return nxt + [head], rst 190 | 191 | 192 | def transConstMap(case_inst: Case, fn_name, filename, args, fv): 193 | body = case_inst.body.insts[:-1] 194 | mk = case_inst.body.insts[-1] 195 | keynames = body[-1] 196 | exprs = [] 197 | rest = body[:-1] 198 | args = case_inst.head.args 199 | while rest: 200 | expr, rest = partitionInst(rest, 1) 201 | exprs.append(expr) 202 | lms = [exprToLambda(e, fn_name, filename, args, fv) for e in reversed(exprs)] 203 | free_vars = set() 204 | for _, fvs in lms: 205 | if fvs: 206 | free_vars.update(fvs) 207 | resbc = bc.Bytecode( 208 | sum( 209 | map(get0, lms), 210 | start=( 211 | [bc.Instr("PUSH_NULL")] 212 | if sys.version_info.major == 3 and sys.version_info.minor >= 11 213 | else [] 214 | ), 215 | ) 216 | ) 217 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 218 | for cell in free_vars: 219 | resbc.insert(0, bc.Instr("MAKE_CELL", bc.CellVar(cell))) 220 | resbc.append(keynames) 221 | resbc.append(mk) 222 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 223 | resbc.append(bc.Instr("LOAD_METHOD", "get")) 224 | for arg in args: 225 | resbc.append(bc.Instr("LOAD_FAST", arg)) 226 | if len(args) > 1: 227 | resbc.append(bc.Instr("BUILD_TUPLE", arg=len(args))) 228 | resbc.extend(generateDefault(fn_name, filename, args)) 229 | resbc.append(bc.Instr("PRECALL", 2)) 230 | resbc.append(bc.Instr("CALL", 2)) 231 | for arg in args: 232 | resbc.append(bc.Instr("LOAD_FAST", arg)) 233 | resbc.append(bc.Instr("PRECALL", arg=len(args))) 234 | resbc.append(bc.Instr("CALL", arg=len(args))) 235 | else: 236 | resbc.append(bc.Instr("LOAD_METHOD", "get")) 237 | for arg in args: 238 | resbc.append(bc.Instr("LOAD_FAST", arg)) 239 | resbc.append(bc.Instr("BUILD_TUPLE", arg=len(args))) 240 | resbc.extend(generateDefault(fn_name, filename, args)) 241 | resbc.append(bc.Instr("CALL_METHOD", 2)) 242 | for arg in args: 243 | resbc.append(bc.Instr("LOAD_FAST", arg)) 244 | resbc.append(bc.Instr("CALL_FUNCTION", arg=len(args))) 245 | resbc.extend(case_inst.store.instrs) 246 | return resbc 247 | 248 | def transVarMap(case_inst : Case, fn_name, filename, args, fv): 249 | body = case_inst.body.insts[:-1] 250 | mk = case_inst.body.insts[-1] 251 | parts = [] 252 | rest = body 253 | hasDefault = False 254 | defaultExpr = [] 255 | args = case_inst.head.args 256 | free_vars = set() 257 | while rest: 258 | part, rest = partitionInst(rest, 2) 259 | expr, pat = partitionInst(part, 1) 260 | if isWildcard(pat[0]) and len(pat) == 1: 261 | assert not hasDefault, f"Duplicated default cases in {fn_name}, line {pat[0].lineno} @ {filename}" 262 | hasDefault = True 263 | defaultExpr, fvs = exprToLambda(expr, fn_name, filename, args, fv) 264 | free_vars.update(fvs) 265 | else: 266 | vbind = {} 267 | vpat = [] 268 | mkTpl = pat[-1] 269 | raw_pat_parts = pat[:-1] # fromRight([[], []], many(globalName | one(const(True)))(pat[:-1]))[0] 270 | pat_parts = [] 271 | while raw_pat_parts: 272 | pat_part, raw_pat_parts = partitionInst(raw_pat_parts, 1) 273 | pat_parts.append(pat_part) 274 | for i, v in enumerate(reversed(pat_parts)): 275 | if len(v) == 1 and isVar(v[0]): 276 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 277 | vbind[v[0].arg[1]] = args[i] 278 | vpat.append(bc.Instr("LOAD_CONST", pat_core._v(v[0].arg[1]))) 279 | else: 280 | vbind[v[0].arg] = args[i] 281 | vpat.append(bc.Instr("LOAD_CONST", pat_core._v(v[0].arg))) 282 | else: 283 | vpat.extend(v) 284 | vpat.append(mkTpl) 285 | lm, fvs = exprToLambda(expr, fn_name, filename, args, fv, vbind) 286 | parts.append((vpat, lm)) 287 | free_vars.update(fvs) 288 | if not hasDefault: 289 | defaultExpr = generateDefault(fn_name, filename, args) 290 | defaultPat = [] 291 | for _ in args: 292 | defaultPat.append(bc.Instr("LOAD_CONST", pat_core._v())) 293 | # if len(args) > 1: 294 | defaultPat.append(bc.Instr("BUILD_TUPLE", len(args))) 295 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 296 | resbc = bc.Bytecode([bc.Instr("PUSH_NULL"), bc.Instr("PUSH_NULL"), bc.Instr("LOAD_CONST", pat_core.pytternd)]) 297 | else: 298 | resbc = bc.Bytecode([bc.Instr("LOAD_CONST", pat_core.pytternd)]) 299 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 300 | for cell in free_vars: 301 | resbc.insert(0, bc.Instr("MAKE_CELL", bc.CellVar(cell))) 302 | for pat, expr in reversed(parts): 303 | resbc.extend(pat) 304 | resbc.extend(expr) 305 | resbc.extend(defaultPat) 306 | resbc.extend(defaultExpr) 307 | if not hasDefault: 308 | mk.arg += 1 309 | resbc.append(mk) 310 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 311 | resbc.append(bc.Instr("PRECALL", 1)) 312 | resbc.append(bc.Instr("CALL", 1)) 313 | else: 314 | resbc.append(bc.Instr("CALL_FUNCTION", 1)) 315 | for arg in args: 316 | resbc.append(bc.Instr("LOAD_FAST", arg)) 317 | # if len(args) > 1: 318 | resbc.append(bc.Instr("BUILD_TUPLE", arg=len(args))) 319 | resbc.append(bc.Instr("BINARY_SUBSCR")) 320 | for arg in args: 321 | resbc.append(bc.Instr("LOAD_FAST", arg)) 322 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 323 | resbc.append(bc.Instr("PRECALL", arg=len(args))) 324 | resbc.append(bc.Instr("CALL", arg=len(args))) 325 | else: 326 | resbc.append(bc.Instr("CALL_FUNCTION", arg=len(args))) 327 | resbc.extend(case_inst.store.instrs) 328 | return resbc 329 | 330 | @func 331 | def handleCases(fn_name, filename, args, fv, instr): 332 | if not isinstance(instr, Case): 333 | return [instr] 334 | if mkConstMap(instr.body.insts[-1]): 335 | return transConstMap(instr, fn_name, filename, args, fv) 336 | elif mkMap(instr.body.insts[-1]): 337 | return transVarMap(instr, fn_name, filename, args, fv) 338 | 339 | loadCase = and_(isLoadGlobal, __.arg ^ get1 == "case") 340 | 341 | def extractGlobalName(i): 342 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 343 | return bc.Instr("LOAD_FAST", i.arg[1]) 344 | return bc.Instr("LOAD_FAST", i.arg) 345 | 346 | globalName = ptrans(one(isLoadGlobal), trans0(trans0(extractGlobalName))) 347 | 348 | parseCaseHead = ptrans( 349 | one(loadCase) >> many1(one(isArg) | globalName) << callInst, 350 | trans0(mp1(__.arg) ^ (lambda x: [CaseHead(x)])), 351 | ) 352 | 353 | parseStoreName = ( 354 | ptrans(one(popTop), trans0(trans0(const(StoreName([bc.Instr("POP_TOP")]))))) 355 | | ptrans(one(storeFast), trans0(lambda x: [StoreName(x)])) 356 | | ptrans(one(unpack) + many1(one(storeFast)), trans0(lambda x: [StoreName(x)])) 357 | ) 358 | 359 | parseCaseBody = ptrans( 360 | many1(neg(or_(mkConstMap, mkMap))) + one(or_(mkConstMap, mkMap)) << callInst, 361 | trans0((lambda x: [CaseBody(x)])), 362 | ) 363 | parseCase = many(parseCaseHead + parseCaseBody + parseStoreName | one(const(True))) 364 | 365 | mergeCase = many(ptrans( 366 | one(is_(CaseHead)) + one(is_(CaseBody)) + one(is_(StoreName)), 367 | trans0((lambda x: [Case(*x)])) 368 | ) | one(const(True))) 369 | 370 | @do(Just) 371 | def deco(b, fn_name, filename, args, freevars): 372 | transBc <- (rightToMaybe(parseCase(b)) | get0) 373 | mergeCase <- (rightToMaybe(mergeCase(transBc)) | get0) 374 | return bc.Bytecode(sum(mp1(handleCases(fn_name, filename, args, freevars), mergeCase), start = [])) 375 | 376 | 377 | def case(fn): 378 | rawbc = bc.Bytecode.from_code(fn.__code__) 379 | argcount = fn.__code__.co_argcount + (1 if isVarargFn(fn) else 0) 380 | args = fn.__code__.co_varnames[:argcount] 381 | 382 | # print( f"Generating pattern matching for function: {fn.__name__} at line: {rawbc.first_lineno} @ {rawbc.filename}") 383 | resbc = deco(rawbc, fn.__name__, rawbc.filename, args, rawbc.freevars) 384 | assert isJust( 385 | resbc 386 | ), f"Failed to generate pattern matching for function: {fn.__name__} at line: {rawbc.first_lineno} @ {rawbc.filename}" 387 | res = fromJust(resbc) 388 | # print(f"{res = }") 389 | cells = set(rawbc.cellvars) 390 | for inst in res: 391 | if isInstr(inst) and inst.name == "MAKE_CELL": 392 | cells.add(inst.arg.name) 393 | res.freevars.extend(rawbc.freevars) 394 | res.cellvars.extend(cells) 395 | res.argcount = rawbc.argcount 396 | res.argnames.extend(rawbc.argnames) 397 | res.name = rawbc.name 398 | res.filename = rawbc.filename 399 | res.flags = rawbc.flags 400 | res.update_flags() 401 | fn.__code__ = res.to_code() 402 | # print("=" * 20) 403 | # dis.dis(fn) 404 | # dis.show_code(fn) 405 | # print("=" * 20) 406 | return fn 407 | 408 | -------------------------------------------------------------------------------- /fpy/experimental/do.py: -------------------------------------------------------------------------------- 1 | import bytecode as bc 2 | 3 | import pprint 4 | 5 | from fpy.parsec.parsec import parser, ptrans, one, many 6 | from fpy.composable.collections import ( 7 | of_, 8 | is_, 9 | and_, 10 | or_, 11 | trans0, 12 | fwd_, 13 | get0, 14 | mp1, 15 | apply, 16 | ) 17 | from fpy.data.function import id_, const 18 | from fpy.data.forgetful import forget 19 | from fpy.data.maybe import Just, isJust, fromJust 20 | from fpy.data.either import Left, Right, rights, either 21 | from fpy.utils.placeholder import __ 22 | from fpy.composable.function import func 23 | from fpy.debug.debug import trace 24 | 25 | from dataclasses import dataclass 26 | 27 | import dis 28 | import sys 29 | 30 | pp = pprint.PrettyPrinter(indent=4) 31 | 32 | @dataclass 33 | class Then: 34 | lineno: int 35 | 36 | 37 | @dataclass 38 | class Arrow: 39 | lineno: int 40 | 41 | 42 | @dataclass 43 | class TupleArrow: 44 | lineno: int 45 | ntpl: int 46 | 47 | 48 | @dataclass 49 | class Ret: 50 | lineno: int 51 | 52 | 53 | isInstr = is_(bc.Instr) 54 | isArrow = is_(Arrow) 55 | dash = and_(isInstr, __.name == "UNARY_NEGATIVE") 56 | arrowHead = and_(isInstr, and_(__.name == "COMPARE_OP", __.arg == bc.Compare.LT)) 57 | popTop = and_(isInstr, __.name == "POP_TOP") 58 | none = and_(isInstr, and_(__.name == "LOAD_CONST", __.arg == None)) 59 | mkTpl = and_(isInstr, __.name == "BUILD_TUPLE") 60 | ret = and_(isInstr, __.name == "RETURN_VALUE") 61 | load = and_( 62 | isInstr, 63 | __.name 64 | ^ of_( 65 | "LOAD_GLOBAL", 66 | "LOAD_NAME", 67 | "LOAD_FAST", 68 | "LOAD_CLOSURE", 69 | "LOAD_DEREF", 70 | "LOAD_CLASSDEREF", 71 | ), 72 | ) 73 | store = and_( 74 | isInstr, 75 | __.name 76 | ^ of_( 77 | "STORE_FAST", 78 | "STORE_NAME", 79 | "STORE_DEREF", 80 | ), 81 | ) 82 | parseArrow = ptrans( 83 | one(dash) << one(arrowHead) << one(popTop), 84 | trans0(trans0(__.lineno ^ Arrow)), 85 | ) 86 | parseTplArrow = ptrans( 87 | one(dash) >> one(arrowHead) >> one(mkTpl) << one(popTop), 88 | trans0(trans0(lambda x: TupleArrow(x.lineno, x.arg))), 89 | ) 90 | parseThen = ptrans( 91 | one(popTop), 92 | trans0(trans0(__.lineno ^ Then)), 93 | ) 94 | parseNoneRet = many( 95 | ptrans( 96 | one(popTop) << one(none) << one(ret), 97 | trans0(trans0(__.lineno ^ Ret)), 98 | ) 99 | | one(const(True)) 100 | ) 101 | 102 | parseDo = many(parseTplArrow | parseArrow | parseThen | one(const(True))) 103 | isFast = and_(isInstr, __.name == "LOAD_FAST") 104 | fastToCell = ptrans( 105 | one(isFast), 106 | trans0(trans0(__.arg ^ bc.CellVar ^ func(bc.Instr, "LOAD_DEREF"))), 107 | ) 108 | isSFast = and_(isInstr, __.name == "STORE_FAST") 109 | storeFastToCell = ptrans( 110 | one(isSFast), 111 | trans0(trans0(__.arg ^ bc.CellVar ^ func(bc.Instr, "STORE_DEREF"))), 112 | ) 113 | transFast = many(fastToCell | storeFastToCell | one(const(True))) 114 | 115 | 116 | @dataclass 117 | class ArrowInst: 118 | comp: list 119 | argnames: list 120 | nxt: list 121 | 122 | 123 | def transformRet(insts): 124 | res = [] 125 | for inst in insts: 126 | if isinstance(inst, Ret): 127 | res.append(bc.Instr("RETURN_VALUE", lineno=inst.lineno)) 128 | continue 129 | if ret(inst): 130 | res.append(bc.Instr("LOAD_DEREF", bc.CellVar("!ret"), lineno=inst.lineno)) 131 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 132 | res.append(bc.Instr("PUSH_NULL")) 133 | res.append(bc.Instr("SWAP", 3, lineno=inst.lineno)) 134 | res.append(bc.Instr("PRECALL", 1)) 135 | res.append(bc.Instr("CALL", 1)) 136 | else: 137 | res.append(bc.Instr("ROT_TWO", lineno=inst.lineno)) 138 | res.append(bc.Instr("CALL_FUNCTION", 1, lineno=inst.lineno)) 139 | # res.append(bc.Instr("DUP_TOP", lineno=inst.lineno)) 140 | # res.append(bc.Instr("PRINT_EXPR", lineno=inst.lineno)) 141 | res.append(bc.Instr("RETURN_VALUE", lineno=inst.lineno)) 142 | continue 143 | res.append(inst) 144 | return res 145 | 146 | 147 | def partitionInst(insts, n): 148 | if not insts: 149 | return [], [] 150 | if n == 0: 151 | return [], insts 152 | head = insts[-1] 153 | # print(f"{head = }") 154 | # print(f"{n = }") 155 | pre, post = head.pre_and_post_stack_effect() 156 | # print(f"{pre = }") 157 | # print(f"{post= }") 158 | if pre >= 0: 159 | if pre == n: 160 | return [head], insts[:-1] 161 | if pre < n: 162 | nxt, rst = partitionInst(insts[:-1], n - pre) 163 | return nxt + [head], rst 164 | pre = abs(pre) 165 | nxt, rst = partitionInst(insts[:-1], pre) 166 | if post == n: 167 | return nxt + [head], rst 168 | if post < n: 169 | head = nxt + [head] 170 | nxt, rst = partitionInst(rst, n - post) 171 | return nxt + head, rst 172 | 173 | 174 | def transformDo(insts): 175 | # pp.pprint(insts) 176 | res = [] 177 | while insts: 178 | inst = insts.pop() 179 | if not isinstance(inst, (Then, Arrow, TupleArrow)): 180 | res.insert(0, inst) 181 | continue 182 | if isinstance(inst, Then): 183 | # a >> b := a >>= \_ -> b 184 | comp, insts = partitionInst(insts, 1) 185 | res = [ArrowInst(comp, [f"!_{inst.lineno}"], res)] 186 | continue 187 | if isinstance(inst, Arrow): 188 | comp, insts = partitionInst(insts, 1) 189 | bindName = insts.pop() 190 | assert load(bindName) or ( 191 | isInstr(bindName) and bindName.name == "BUILD_TUPLE" 192 | ), "it has to be tuple of symbols on the left of <-" 193 | if load(bindName): 194 | name = bindName.arg 195 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 196 | if isinstance(name, tuple): 197 | name = name[1] 198 | res = [ArrowInst(comp, [name], res)] 199 | continue 200 | if isInstr(bindName) and bindName.name == "BUILD_TUPLE": 201 | narg = bindName.arg 202 | names = [] 203 | for _ in range(narg): 204 | name = insts.pop() 205 | assert load(name), "it has to be tuple of symbols on the left of <-" 206 | if sys.version_info.major == 3 and sys.version_info.minor >= 11 and isinstance(name.arg, tuple): 207 | names.insert(0, name.arg[1]) 208 | else: 209 | names.insert(0, name.arg) 210 | res = [ArrowInst(comp, names, res)] 211 | continue 212 | elif isinstance(inst, TupleArrow): 213 | comp, insts = partitionInst(insts, 1) 214 | names = [] 215 | for _ in range(inst.ntpl): 216 | name = insts.pop() 217 | assert load(name), "it has to be tuple of symbols on the left of <-" 218 | if sys.version_info.major == 3 and sys.version_info.minor >= 11 and isinstance(name.arg, tuple): 219 | names.insert(0, name.arg[1]) 220 | else: 221 | names.insert(0, name.arg) 222 | res = [ArrowInst(comp, names, res)] 223 | continue 224 | 225 | return res 226 | 227 | 228 | def generateLocal(insts, argnames, fv, cv, name, filename): 229 | resBc = [] 230 | bcobj = bc.Bytecode(resBc) 231 | bcobj.freevars = fv 232 | bcobj.cellvars = cv 233 | bcobj.name = name 234 | bcobj.filename = filename 235 | bcobj.docstring = "generated local function for binding in do notation" 236 | bcobj.argcount = 1 237 | bcobj.argname.extend(argnames) 238 | co = bcobj.to_code() 239 | return co 240 | 241 | 242 | def build_do_func(name, arg, body, free): 243 | inner = doDeco(body, name, arg, free) 244 | return inner 245 | 246 | 247 | def markArg(args): 248 | def res(x): 249 | if load(x): 250 | if sys.version_info.major == 3 and sys.version_info.minor >= 11 and isinstance(x.arg, tuple): 251 | if x.arg[1] in args: 252 | return Right(bc.Instr("LOAD_CONST", x.arg[1])) 253 | else: 254 | return Left(x) 255 | else: 256 | return Right(x) if load(x) and x.arg in args else Left(x) 257 | else: 258 | return Left(x) 259 | return res 260 | 261 | toArg = __.arg ^ bc.CellVar ^ func(bc.Instr, "LOAD_DEREF") 262 | # toArg = __.arg ^ func(bc.Instr, "LOAD_FAST") 263 | isCell = and_( 264 | isInstr, 265 | and_( 266 | __.name ^ of_("LOAD_DEREF", "STORE_DEREF", "LOAD_CLOSURE"), 267 | __.arg ^ is_(bc.CellVar), 268 | ), 269 | ) 270 | transFree = lambda free: ( 271 | lambda x: bc.Instr("LOAD_DEREF", bc.FreeVar(x.arg)) 272 | if and_(isInstr, and_(__.name == "LOAD_GLOBAL", __.arg ^ of_(*free)))(x) 273 | else x 274 | ) 275 | markFree = lambda free: ( 276 | lambda x: Right(x) if isCell(x) and x.arg.name in free else Left(x) 277 | ) 278 | toFree = lambda x: bc.Instr(x.name, bc.FreeVar(x.arg.name)) 279 | 280 | 281 | @func 282 | def doArrow(name, cells, free, arrow): 283 | if not isinstance(arrow, ArrowInst): 284 | return [arrow] 285 | # print(f"doing arrow: {arrow}") 286 | bind_fn_name = f"{name}.__do_bind_{'_'.join(arrow.argnames)}__" 287 | # print(f"{bind_fn_name = }") 288 | arrfn = build_do_func(bind_fn_name, arrow.argnames, arrow.nxt, [*cells, *free]) 289 | # print("=" * 20) 290 | # dis.dis(arrfn) 291 | # dis.show_code(arrfn) 292 | # print("=" * 20) 293 | # print(f"{bind_fn_name = }") 294 | rawcomp = arrow.comp 295 | # print(f"{rawcomp = }") 296 | transcomp = ( 297 | mp1(markArg([arrow.argnames, *free, *cells])) 298 | ^ mp1(either(id_, toArg)) 299 | ^ mp1(markFree(free)) 300 | ^ mp1(either(id_, toFree)) 301 | ^ transFree(free) 302 | )(rawcomp) 303 | # print(f"{transcomp = }") 304 | res = [ 305 | *transcomp, 306 | * ([bc.Instr("LOAD_METHOD", "__bind__", lineno=arrow.comp[-1].lineno)] 307 | if sys.version_info.major == 3 and sys.version_info.minor >= 11 else 308 | [bc.Instr("LOAD_ATTR", "__bind__", lineno=arrow.comp[-1].lineno)]) 309 | ] 310 | ncells = len(cells) 311 | for cell in cells: 312 | res.append(bc.Instr("LOAD_CLOSURE", bc.CellVar(cell))) 313 | for f in free: 314 | if f not in cells: 315 | res.append(bc.Instr("LOAD_CLOSURE", bc.FreeVar(f))) 316 | ncells += 1 317 | if cells: 318 | res.append(bc.Instr("BUILD_TUPLE", ncells)) 319 | res.append(bc.Instr("LOAD_CONST", arrfn)) 320 | if not (sys.version_info.major == 3 and sys.version_info.minor >= 11): 321 | res.append( 322 | bc.Instr( 323 | "LOAD_CONST", 324 | bind_fn_name, 325 | lineno=arrow.comp[-1].lineno, 326 | ) 327 | ) 328 | res.append(bc.Instr("MAKE_FUNCTION", 0x08, lineno=arrow.comp[-1].lineno)) 329 | if len(arrow.argnames) > 1: 330 | res.append(bc.Instr("LOAD_CONST", apply)) 331 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 332 | res.append(bc.Instr("PUSH_NULL")) 333 | res.append(bc.Instr("SWAP", 3)) 334 | res.append(bc.Instr("PRECALL", 1)) 335 | res.append(bc.Instr("CALL", 1)) 336 | else: 337 | res.append(bc.Instr("ROT_TWO")) 338 | res.append(bc.Instr("CALL_FUNCTION", 1)) 339 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 340 | res.append(bc.Instr("PRECALL", 1)) 341 | res.append(bc.Instr("CALL", 1)) 342 | else: 343 | res.append(bc.Instr("CALL_FUNCTION", 1, lineno=arrow.comp[-1].lineno)) 344 | res.append(bc.Instr("RETURN_VALUE", lineno=arrow.comp[-1].lineno)) 345 | return res 346 | 347 | def makeCells(insts): 348 | cells = set() 349 | for inst in insts: 350 | if not isInstr(inst): 351 | continue 352 | if inst.name != 'MAKE_CELL': 353 | continue 354 | if inst.arg.name not in cells: 355 | cells.add(inst.arg.name) 356 | return cells 357 | 358 | def doDeco(b, name, args, free): 359 | # print(f"{free = }") 360 | # print("RAW BC: ", b) 361 | res = ( 362 | parseDo(b) >> (get0 ^ transFast) & forget 363 | | get0 364 | ^ mp1(markFree(free)) 365 | ^ mp1(either(id_, toFree)) 366 | ^ mp1(markArg(args)) 367 | ^ mp1(either(id_, toArg)) 368 | ^ mp1(transFree(free)) 369 | # ^ trace("before trans do = ") 370 | ^ transformDo 371 | ) 372 | # print("Trans BC: ", res.under()) 373 | getCellName = lambda x: Right(x) if isCell(x) else Left(x) 374 | cells = res | mp1(getCellName) | rights | mp1(__.arg.name) | __ + list(args) | set 375 | # print(f"{cells = }") 376 | res = ( 377 | res 378 | # | trace("res = ") 379 | | mp1(doArrow(name, cells.under(), free)) 380 | # | trace("didArrow = ") 381 | | func(sum, start=[]) ^ bc.Bytecode 382 | ) 383 | # print(f"{res.under() = }") 384 | resbc = res.under() 385 | 386 | madeCells = makeCells(resbc) 387 | 388 | # pp.pprint(resbc) 389 | resbc.cellvars.extend(cells.under()) 390 | resbc.cellvars.extend(free) 391 | if sys.version_info.major == 3 and sys.version_info.minor >= 11: 392 | for cell in resbc.cellvars: 393 | if cell not in madeCells: 394 | resbc.insert(0, bc.Instr("MAKE_CELL", bc.CellVar(cell))) 395 | resbc.freevars.extend(free) 396 | if len(resbc.freevars) > 0: 397 | resbc.insert(0, bc.Instr("COPY_FREE_VARS", len(resbc.freevars))) 398 | resbc.argcount = len(args) 399 | resbc.argnames.extend(args) 400 | resbc.name = name 401 | resbc.filename = name 402 | resbc.flags = resbc.flags | 16 403 | resbc.update_flags() 404 | co = resbc.to_code() 405 | # print("======================") 406 | # print(name) 407 | # print("======================") 408 | # dis.dis(co) 409 | # dis.show_code(co) 410 | return co 411 | 412 | 413 | def do(m): 414 | def res(fn): 415 | ret = m 416 | # add `!ret` to the front of function 417 | retbc = [ 418 | bc.Instr("LOAD_CONST", m), 419 | bc.Instr("LOAD_ATTR", "ret"), 420 | bc.Instr("STORE_DEREF", bc.CellVar("!ret")), 421 | ] 422 | rawbc = bc.Bytecode.from_code(fn.__code__) 423 | # print(f"{rawbc = }") 424 | args = fn.__code__.co_varnames[: fn.__code__.co_argcount] 425 | b = parseNoneRet(retbc + rawbc) & forget | get0 | transformRet 426 | co = doDeco(b.under(), fn.__name__, args, rawbc.freevars) 427 | fn.__code__ = co 428 | return fn 429 | 430 | return res 431 | -------------------------------------------------------------------------------- /fpy/experimental/pattern/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Z-Shang/fpy/16463b895dcde8d1b9da7048e795d5084b6e138c/fpy/experimental/pattern/__init__.py -------------------------------------------------------------------------------- /fpy/experimental/pattern/core.py: -------------------------------------------------------------------------------- 1 | def _fresh(*n, _rec={}): 2 | v = _rec.get(n, 0) + 1 3 | _rec[n] = v 4 | return "_{}_{}".format("_".join(n), v) 5 | 6 | 7 | class _v: 8 | def __init__(self, n=None): 9 | self.n = n or _fresh("_v") 10 | 11 | def __hash__(self): 12 | return hash(self.n) 13 | 14 | def __repr__(self): 15 | return self.__str__() 16 | 17 | def __str__(self): 18 | return "#v<{}>".format(self.n) 19 | 20 | def __call__(self, *args, **kw): 21 | raise TypeError(f"_v Object is not callable, {self} called with: {args}, {kw}") 22 | 23 | 24 | class NonExhaustivePatternError(Exception): 25 | def __init__(self, msg): 26 | self.msg = msg 27 | super().__init__(self.msg) 28 | 29 | 30 | class pytternd: 31 | """ 32 | usage: 33 | pytternd( 34 | { 35 | (1, 2, 3): True 36 | (_v(1), _v(2), 4): False 37 | ... 38 | } 39 | )[1, 2, 4] = False 40 | 41 | referencing variable in body is not supported until this is made into a decorator 42 | """ 43 | 44 | def __init__(self, d: dict): 45 | self.orig_d = d 46 | # print(f"{d = }") 47 | self.varp = dict() 48 | patlen = [len(k) for k in d.keys()] 49 | assert len(set(patlen)) == 1, "Currently patterns must of same length" 50 | self._len = patlen[0] 51 | self._prepare(d) 52 | 53 | def _prepare(self, d: dict): 54 | ks = list(d.keys()) 55 | if not ks: 56 | return d 57 | assert not self._check_overlap_q(ks), "Cannot have overlapping patterns" 58 | if len(ks[0]) == 1: 59 | varp = {} 60 | res = {} 61 | for k, v in d.items(): 62 | if isinstance(k[0], _v): 63 | varp[()] = v 64 | continue 65 | res[k[0]] = v 66 | self.varp = varp 67 | self.d = res 68 | return 69 | new = {} 70 | varp = {} 71 | for k, v in d.items(): 72 | if isinstance(k[0], _v): 73 | varp[k[1:]] = v 74 | continue 75 | new[k[0]] = {k[1:]: v, **new.get(k[0], {})} 76 | if varp: 77 | self.varp = pytternd(varp) 78 | self.d = {k: pytternd(v) for k, v in new.items()} if len(ks[0]) > 1 else new 79 | 80 | def _check_overlap_q(self, ks): 81 | if len(ks[0]) > 1: 82 | return False 83 | return all([isinstance(k, _v) for k in ks]) 84 | 85 | def __getitem__(self, vs): 86 | x, *xs = vs 87 | assert len(vs) == self._len, "Number of value doesn't match pattern length" 88 | 89 | if xs: 90 | try: 91 | return self.d[x].__getitem__(xs) 92 | except Exception as e: 93 | if self.varp: 94 | return self.varp.__getitem__(xs) 95 | raise NonExhaustivePatternError( 96 | "There is no pattern matching value: {}".format(vs) 97 | ) from None 98 | try: 99 | return self.d[x] 100 | except: 101 | try: 102 | return self.varp[()] 103 | except: 104 | raise NonExhaustivePatternError( 105 | "There is no pattern matching value: {}".format(vs) 106 | ) from None 107 | 108 | def match(self, *vs, default=None): 109 | try: 110 | return self.__getitem__(vs) 111 | except NonExhaustivePatternError: 112 | return default 113 | 114 | def __len__(self): 115 | return self._len 116 | 117 | def __repr__(self): 118 | return str({**self.d, **({"": self.varp} if self.varp else {})}) 119 | 120 | 121 | if __name__ == "__main__": 122 | test = pytternd( 123 | {(1, 2, 3): True, (_v(1), _v(2), 4): False, (_v(1), _v(2), _v(3)): "Huh?"} 124 | ) 125 | print(test[1, 2, 3]) 126 | print(test[1, 2, 4]) 127 | print(test[1, 2, 5]) 128 | -------------------------------------------------------------------------------- /fpy/parsec/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Z-Shang/fpy/16463b895dcde8d1b9da7048e795d5084b6e138c/fpy/parsec/__init__.py -------------------------------------------------------------------------------- /fpy/parsec/parsec.py: -------------------------------------------------------------------------------- 1 | from fpy.data.either import Either, Left, Right, isRight, fromRight 2 | from fpy.data.forgetful import forget 3 | from fpy.data.function import const, flip 4 | from fpy.utils.placeholder import __ 5 | from fpy.composable.transparent import Transparent 6 | from fpy.composable.function import func 7 | from fpy.composable.collections import ( 8 | apply, 9 | transN, 10 | trans0, 11 | trans1, 12 | or_, 13 | and_, 14 | set0, 15 | set1, 16 | get0, 17 | get1, 18 | ) 19 | 20 | import string 21 | from typing import TypeVar, List, Tuple, Callable, Generic, Sequence, Union, Optional, Any 22 | from dataclasses import dataclass 23 | import collections.abc as cabc 24 | 25 | S = TypeVar("S") 26 | T = TypeVar("T") 27 | 28 | 29 | def isspace(c): 30 | return c in string.whitespace 31 | 32 | 33 | def s2c(s: str) -> List[str]: 34 | return list(s) 35 | 36 | 37 | def c2s(cs: List[str]) -> str: 38 | return "".join(cs) 39 | 40 | 41 | @dataclass 42 | class parser(Transparent, Generic[S, T]): 43 | """ 44 | parser :: [S] -> Either [S] ([T] * [S]) 45 | """ 46 | 47 | fn: Union[Callable[[Sequence[S]], Either[Any, Tuple[T, Sequence[S]]]], Callable[[Sequence[S]], Optional[Tuple[T, Sequence[S]]]]] 48 | 49 | def __underlying__(self): 50 | return self.fn 51 | 52 | def __call__(self, s: Sequence[S]): 53 | if not isinstance(s, cabc.Sequence): 54 | raise TypeError("Cannot parse none sequence") 55 | if not s: 56 | return Left(s) 57 | res = self.fn(s) 58 | if res is None: 59 | return Left(s) 60 | assert isinstance(res, (tuple, Either)), f"{res} type is {type(res)}" 61 | return Right(res) if isinstance(res, tuple) else res 62 | 63 | def timeN(self, n): 64 | if n <= 0: 65 | return parser(const(None)) 66 | 67 | p = self 68 | for n in range(n - 1): 69 | p = p + self 70 | 71 | return p 72 | 73 | def __mul__(self, n): 74 | return self.timeN(n) 75 | 76 | def __rmul__(self, n): 77 | return self.timeN(n) 78 | 79 | def concat(self, nxt): 80 | @parser 81 | def __concat(s): 82 | return self(s) >> apply(lambda a, rest: nxt(rest) | trans0(a + __)) 83 | 84 | return __concat 85 | 86 | def __add__(self, nxt): 87 | return self.concat(nxt) 88 | 89 | def choice(self, other): 90 | @parser 91 | def __choice(s): 92 | return or_(self, other)(s) or None 93 | 94 | return __choice 95 | 96 | def __or__(self, other): 97 | return self.choice(other) 98 | 99 | def parseR(self, rightP): 100 | @parser 101 | def __parseR(s): 102 | return self(s) >> apply(lambda leftR, rest: rightP(rest)) 103 | 104 | return __parseR 105 | 106 | def parseL(self, rightP): 107 | @parser 108 | def __parseL(s): 109 | return self(s) >> apply(lambda leftR, rest: rightP(rest) | set0(leftR)) 110 | 111 | return __parseL 112 | 113 | def __rshift__(self, other): 114 | return self.parseR(other) 115 | 116 | def __lshift__(self, other): 117 | return self.parseL(other) 118 | 119 | 120 | def one(pred: Callable[[S], bool]) -> parser[S, S]: 121 | @parser 122 | def res(s: Sequence[S]): 123 | if pred(s[0]): 124 | return s[0], s[1:] 125 | return None 126 | 127 | return res 128 | 129 | 130 | def neg(pred: Callable[[S], bool]) -> parser[S, S]: 131 | @parser 132 | def res(s: Sequence[S]): 133 | if not pred(s[0]): 134 | return s[0], s[1:] 135 | return None 136 | 137 | return res 138 | 139 | 140 | def just_nothing(unit : T) -> parser[S, T]: 141 | @parser 142 | def __res(s: Sequence[S]): 143 | return (unit, s) 144 | return __res 145 | 146 | def pmaybe(p: parser[S, T], unit: T): 147 | return p | just_nothing(unit) 148 | 149 | 150 | def many1(p: parser[S, Sequence[T]]): 151 | """ 152 | many1 must take a parser that results in a sequence of tokens 153 | """ 154 | @parser 155 | def __many1(s: Sequence[S]) -> Either[Any, Tuple[Sequence[T], Sequence[S]]]: 156 | _res = [] 157 | work_s = s 158 | while work_s: 159 | _part: Either[Any, Tuple[Sequence[T], Sequence[S]]] = p(work_s) 160 | if not isRight(_part): 161 | break 162 | part, work_s = fromRight(([], []), _part) 163 | _res += part 164 | if not _res: 165 | return Left("no res from many1") 166 | return Right((_res, work_s)) 167 | 168 | return __many1 169 | 170 | 171 | many = lambda p: pmaybe(many1(p), []) 172 | 173 | 174 | def ptrans(p, trans): 175 | return parser(lambda s: p(s) | trans) 176 | 177 | 178 | def peek(p): 179 | @parser 180 | def __peek(s): 181 | return p(s) | set1(s) 182 | 183 | return __peek 184 | 185 | 186 | discard = set0([]) 187 | skip = flip(ptrans, discard) 188 | 189 | 190 | def toSeq(p: parser[S, T]) -> parser[S, Sequence[T]]: 191 | return ptrans(p, trans0(lambda x: [x])) 192 | 193 | def pseq(s: Sequence[S]) -> parser[S, Sequence[S]]: 194 | if not s: 195 | return just_nothing([]) 196 | p = just_nothing([]) 197 | for e in s: 198 | p = p + toSeq(one(__ == e)) 199 | return p 200 | 201 | def inv(p): 202 | @parser 203 | def __inv(s): 204 | _r = p(s) 205 | if _r: 206 | return None 207 | return [], s 208 | return __inv 209 | -------------------------------------------------------------------------------- /fpy/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Z-Shang/fpy/16463b895dcde8d1b9da7048e795d5084b6e138c/fpy/tests/__init__.py -------------------------------------------------------------------------------- /fpy/tests/test_composable.py: -------------------------------------------------------------------------------- 1 | from fpy.composable.function import func, SignatureMismatchError, NotEnoughArgsError 2 | from fpy.composable.collections import ( 3 | Seq, 4 | Map, 5 | transN, 6 | setN, 7 | getN, 8 | get0, 9 | of_, 10 | is_, 11 | and_, 12 | or_, 13 | to, 14 | apply, 15 | mapN, 16 | fwd_, 17 | ) 18 | from fpy.data.forgetful import Under 19 | from fpy.utils.placeholder import __ 20 | 21 | import unittest 22 | 23 | 24 | def add1(x): 25 | return x + 1 26 | 27 | 28 | def mul2(x): 29 | return x * 2 30 | 31 | 32 | def pos(x): 33 | return x > 0 34 | 35 | 36 | def odd(x): 37 | return x % 2 != 0 38 | 39 | 40 | def add(a, b): 41 | return a + b 42 | 43 | 44 | class TestCompsable(unittest.TestCase): 45 | def testFunc(self): 46 | f1 = func(add1) 47 | f2 = func(mul2) 48 | self.assertEqual(4, (f1 ^ f2)(1)) 49 | self.assertEqual(3, (f2 ^ f1)(1)) 50 | self.assertEqual(fwd_(1) | f1 ^ f2, Under(4)) 51 | self.assertEqual(fwd_(1) | f2 ^ f1, Under(3)) 52 | 53 | def testSeq(self): 54 | lst = [1, 2, 3, 4, 5] 55 | fn = Seq(lst) 56 | self.assertEqual(1, fn(0)) 57 | self.assertEqual(2, fn(1)) 58 | self.assertEqual(3, fn(2)) 59 | self.assertEqual(4, fn(3)) 60 | self.assertEqual(5, fn(4)) 61 | self.assertEqual(Under(1), fwd_(0) | fn) 62 | self.assertEqual(Under(2), fwd_(1) | fn) 63 | self.assertEqual(Under(3), fwd_(2) | fn) 64 | self.assertEqual(Under(4), fwd_(3) | fn) 65 | self.assertEqual(Under(5), fwd_(4) | fn) 66 | 67 | def testMap(self): 68 | mp = {"a": 1, "b": 2, "c": 3} 69 | fn = Map(mp) 70 | self.assertEqual(1, fn("a")) 71 | self.assertEqual(2, fn("b")) 72 | self.assertEqual(3, fn("c")) 73 | self.assertEqual(Under(1), fwd_("a") | fn) 74 | self.assertEqual(Under(2), fwd_("b") | fn) 75 | self.assertEqual(Under(3), fwd_("c") | fn) 76 | 77 | def testItN(self): 78 | lst = [1, 2, 3] 79 | self.assertListEqual([2, 2, 3], transN(0, add1, lst)) 80 | self.assertListEqual([2, 2, 3], setN(0, 2, lst)) 81 | self.assertEqual(2, getN(1, lst)) 82 | 83 | def testOf(self): 84 | self.assertTrue(of_(1, 2, 3, 4)(2)) 85 | self.assertFalse(of_(1, 2, 3, 4)(5)) 86 | 87 | def testIs(self): 88 | self.assertTrue(is_(int)(1)) 89 | self.assertFalse(is_(str)(1)) 90 | 91 | def testAnd(self): 92 | self.assertTrue(and_(odd, pos)(1)) 93 | self.assertFalse(and_(odd, pos)(2)) 94 | 95 | def testOr(self): 96 | self.assertTrue(or_(odd, pos)(1)) 97 | self.assertTrue(or_(odd, pos)(2)) 98 | 99 | def testTo(self): 100 | fn = to(int) 101 | self.assertEqual(1, fn("1")) 102 | 103 | def testApply(self): 104 | fn = apply(add1) 105 | self.assertEqual(2, fn((1,))) 106 | 107 | def testMapN(self): 108 | f1 = mapN(1, add1) 109 | self.assertListEqual([2, 3, 4], f1([1, 2, 3])) 110 | f2 = mapN(1)(add1) 111 | self.assertListEqual([2, 3, 4], f2([1, 2, 3])) 112 | 113 | def testPlaceholder(self): 114 | class T: 115 | def __init__(self, a): 116 | self.a = a 117 | 118 | a = T(1) 119 | f = __.a == 1 120 | self.assertTrue(f(a)) 121 | 122 | b = T([1,2,3]) 123 | g = __.a ^ get0 == 1 124 | self.assertTrue(g(b)) 125 | -------------------------------------------------------------------------------- /fpy/tests/test_cont.py: -------------------------------------------------------------------------------- 1 | from fpy.data.cont import Cont, cont 2 | from fpy.data.forgetful import forget, Under 3 | from fpy.composable.function import func 4 | 5 | import unittest 6 | 7 | 8 | add = lambda a, b: a + b 9 | mul = lambda a, b: a * b 10 | div = lambda a, b: a / b 11 | 12 | 13 | class TestCont(unittest.TestCase): 14 | def testCont(self): 15 | ac = cont(add) 16 | mc = cont(mul) 17 | dc = cont(div) 18 | res = dc(2, 2) >> mc(3) >> ac(1) 19 | self.assertEqual(Under(4), res & forget) 20 | self.assertEqual(Under(2), ac(1, 1) & forget) 21 | 22 | def testContWithFunc(self): 23 | ac = cont(func(add)) 24 | mc = cont(func(mul)) 25 | dc = cont(func(div)) 26 | res = dc(2, 2) >> mc(3) >> ac(1) 27 | self.assertEqual(Under(4), res & forget) 28 | self.assertEqual(Under(2), ac(1, 1) & forget) 29 | -------------------------------------------------------------------------------- /fpy/tests/test_ctx_do.py: -------------------------------------------------------------------------------- 1 | from fpy.data.maybe import ( 2 | Maybe, 3 | Just, 4 | Nothing, 5 | isJust, 6 | isNothing, 7 | fromJust, 8 | ) 9 | from fpy.control.monad import do 10 | 11 | import unittest 12 | 13 | 14 | def foo(x, y): 15 | return Just(x + y) 16 | 17 | 18 | class TestDo(unittest.TestCase): 19 | def testSimpleJust(self): 20 | @do 21 | def test(): 22 | with Just(1) as x: 23 | return Just(x) 24 | 25 | res = test() 26 | self.assertTrue(isJust(res)) 27 | self.assertEqual(fromJust(res), 1) 28 | 29 | def testSimpleNothing(self): 30 | @do 31 | def test(): 32 | with Just(1) as x: 33 | return Nothing() 34 | 35 | res = test() 36 | self.assertTrue(isNothing(res)) 37 | 38 | def testLocal(self): 39 | @do 40 | def test(): 41 | x = Just(1) 42 | with x as y: 43 | return Just(y) 44 | 45 | res = test() 46 | self.assertTrue(isJust(res)) 47 | self.assertEqual(fromJust(res), 1) 48 | 49 | def testLocalNested(self): 50 | @do 51 | def test(): 52 | x = 1 53 | with Just(2) as y: 54 | with Just(x + y) as z: 55 | return Just(z) 56 | 57 | res = test() 58 | self.assertTrue(isJust(res)) 59 | self.assertEqual(fromJust(res), 3) 60 | 61 | def testNested(self): 62 | @do 63 | def test(): 64 | with Just(1) as x, Just(2) as y, foo(x, y) as z: 65 | return Just(z + z) 66 | 67 | res = test() 68 | self.assertTrue(isJust(res)) 69 | self.assertEqual(fromJust(res), 6) 70 | 71 | def testTuple(self): 72 | @do 73 | def test(): 74 | with Just((1, 2)) as (a, b): 75 | return Just(a + b) 76 | 77 | res = test() 78 | self.assertTrue(isJust(res)) 79 | self.assertEqual(fromJust(res), 3) 80 | 81 | def testComplex(self): 82 | @do 83 | def test(): 84 | with Just((1, 2)) as (a, b), Just(a + b) as c, Just(c * b) as d: 85 | return Just(d) 86 | 87 | res = test() 88 | self.assertTrue(isJust(res)) 89 | self.assertEqual(fromJust(res), 6) 90 | -------------------------------------------------------------------------------- /fpy/tests/test_do.py: -------------------------------------------------------------------------------- 1 | from fpy.data.maybe import ( 2 | Maybe, 3 | Just, 4 | Nothing, 5 | isJust, 6 | isNothing, 7 | fromJust, 8 | ) 9 | from fpy.experimental.do import do 10 | 11 | import unittest 12 | 13 | 14 | def foo(x, y): 15 | return Just(x + y) 16 | 17 | 18 | class TestDo(unittest.TestCase): 19 | def testSimpleJust(self): 20 | @do(Just) 21 | def test(): 22 | x < -Just(1) 23 | return x 24 | 25 | res = test() 26 | self.assertTrue(isJust(res)) 27 | self.assertEqual(fromJust(res), 1) 28 | 29 | def testSimpleNothing(self): 30 | @do(Just) 31 | def test(): 32 | x < -Just(1) 33 | Nothing() 34 | 35 | res = test() 36 | self.assertTrue(isNothing(res)) 37 | 38 | def testLocal(self): 39 | @do(Just) 40 | def test(): 41 | x = Just(1) 42 | y < -x 43 | return y 44 | 45 | res = test() 46 | self.assertTrue(isJust(res)) 47 | self.assertEqual(fromJust(res), 1) 48 | 49 | def testLocalNested(self): 50 | @do(Just) 51 | def test(): 52 | x = 1 53 | y < -Just(2) 54 | z < -Just(x + y) 55 | return z 56 | 57 | res = test() 58 | self.assertTrue(isJust(res)) 59 | self.assertEqual(fromJust(res), 3) 60 | 61 | def testNested(self): 62 | @do(Just) 63 | def test(): 64 | x < -Just(1) 65 | y < -Just(2) 66 | z < -foo(x, y) 67 | return z + z 68 | 69 | res = test() 70 | self.assertTrue(isJust(res)) 71 | self.assertEqual(fromJust(res), 6) 72 | 73 | def testTuple(self): 74 | @do(Just) 75 | def test(): 76 | (a, b) < -Just((1, 2)) 77 | return a + b 78 | 79 | res = test() 80 | self.assertTrue(isJust(res)) 81 | self.assertEqual(fromJust(res), 3) 82 | 83 | def testTupleNoParen(self): 84 | @do(Just) 85 | def test(): 86 | a, b < -Just((1, 2)) 87 | return a + b 88 | 89 | res = test() 90 | self.assertTrue(isJust(res)) 91 | self.assertEqual(fromJust(res), 3) 92 | 93 | def testComplex(self): 94 | @do(Just) 95 | def test(): 96 | a, b <- Just((1, 2)) 97 | c <- Just(a + b) 98 | d <- Just(c * b) 99 | return d 100 | 101 | res = test() 102 | self.assertTrue(isJust(res)) 103 | self.assertEqual(fromJust(res), 6) 104 | -------------------------------------------------------------------------------- /fpy/tests/test_either.py: -------------------------------------------------------------------------------- 1 | from fpy.data.either import ( 2 | Either, 3 | Left, 4 | Right, 5 | isLeft, 6 | isRight, 7 | fromLeft, 8 | fromRight, 9 | either, 10 | lefts, 11 | rights, 12 | partitionEithers, 13 | r2l, 14 | l2r, 15 | ) 16 | from fpy.data.forgetful import forget, Under 17 | 18 | import unittest 19 | 20 | 21 | def even(n) -> Either[int, int]: 22 | if n % 2 == 0: 23 | return Right(n) 24 | return Left(n) 25 | 26 | 27 | def add1(n): 28 | return n + 1 29 | 30 | 31 | def sub1(n): 32 | return n - 1 33 | 34 | 35 | class TestEither(unittest.TestCase): 36 | def testLeft(self): 37 | v = Left(3) 38 | self.assertTrue(isLeft(v)) 39 | self.assertFalse(isRight(v)) 40 | self.assertEqual(3, fromLeft(0, v)) 41 | self.assertEqual(0, fromRight(0, v)) 42 | self.assertEqual(4, either(add1, sub1, v)) 43 | 44 | def testRight(self): 45 | v = Right(3) 46 | self.assertTrue(isRight(v)) 47 | self.assertFalse(isLeft(v)) 48 | self.assertEqual(3, fromRight(0, v)) 49 | self.assertEqual(0, fromLeft(0, v)) 50 | self.assertEqual(2, either(add1, sub1, v)) 51 | 52 | def testEitherList(self): 53 | lst = [even(n) for n in range(8)] 54 | self.assertListEqual(lefts(lst), [1, 3, 5, 7]) 55 | self.assertListEqual(rights(lst), [0, 2, 4, 6]) 56 | ls, rs = partitionEithers(lst) 57 | self.assertListEqual(ls, [1, 3, 5, 7]) 58 | self.assertListEqual(rs, [0, 2, 4, 6]) 59 | 60 | def testNTransLeft(self): 61 | v = Left(3) 62 | vforgot = v & forget 63 | self.assertIsInstance(vforgot, Under) 64 | self.assertEqual(3, vforgot.under()) 65 | vr = v & l2r 66 | self.assertTrue(isRight(vr)) 67 | self.assertEqual(3, fromRight(0, vr)) 68 | 69 | def testNTransRight(self): 70 | v = Right(3) 71 | vforgot = v & forget 72 | self.assertIsInstance(vforgot, Under) 73 | self.assertEqual(3, vforgot.under()) 74 | vr = v & r2l 75 | self.assertTrue(isLeft(vr)) 76 | self.assertEqual(3, fromLeft(0, vr)) 77 | -------------------------------------------------------------------------------- /fpy/tests/test_function.py: -------------------------------------------------------------------------------- 1 | from fpy.data.function import id_, const, flip, fix, on, constN, uncurryN 2 | 3 | import unittest 4 | 5 | 6 | def catInt(a: str, b: int) -> str: 7 | return a + str(b) 8 | 9 | 10 | def add(a: int, b: int) -> int: 11 | return a + b 12 | 13 | 14 | class TestFunction(unittest.TestCase): 15 | def testId(self): 16 | v = id_(1) 17 | self.assertEqual(1, v) 18 | 19 | def testConst(self): 20 | f = const(1) 21 | self.assertEqual(1, f(123)) 22 | 23 | def testFlip(self): 24 | a = 123 25 | b = "hello" 26 | f = flip(catInt) 27 | self.assertEqual("hello123", f(a, b)) 28 | 29 | def testOn(self): 30 | a = "1" 31 | b = "2" 32 | f = on(add, int) 33 | self.assertEqual(3, f(a, b)) 34 | 35 | def testFix(self): 36 | _fib = lambda r, n: 1 if n <= 1 else n * r(n - 1) 37 | fib = fix(_fib) 38 | self.assertEqual(120, fib(5)) 39 | 40 | def testConstN(self): 41 | f = constN(3, 42) 42 | self.assertEqual(42, f(1)(2)(3)) 43 | 44 | def testUncurryN(self): 45 | f = constN(3, 42) 46 | uf = uncurryN(3, f) 47 | self.assertEqual(42, uf(1, 2, 3)) 48 | 49 | def testUncurryNErr(self): 50 | f = constN(3, 42) 51 | uf = uncurryN(3, f) 52 | with self.assertRaises(TypeError): 53 | uf(1, 2) 54 | -------------------------------------------------------------------------------- /fpy/tests/test_maybe.py: -------------------------------------------------------------------------------- 1 | from fpy.data.maybe import ( 2 | Maybe, 3 | Just, 4 | Nothing, 5 | isJust, 6 | isNothing, 7 | fromJust, 8 | fromMaybe, 9 | maybe, 10 | mapMaybe, 11 | ) 12 | from fpy.data.forgetful import forget, Under 13 | 14 | import unittest 15 | 16 | 17 | def add1(x): 18 | return x + 1 19 | 20 | 21 | def even(n: int) -> Maybe[int]: 22 | if n % 2 == 0: 23 | return Just(n) 24 | return Nothing() 25 | 26 | 27 | class TestMaybe(unittest.TestCase): 28 | def testJust(self): 29 | v = Just(3) 30 | self.assertTrue(isJust(v)) 31 | self.assertFalse(isNothing(v)) 32 | self.assertEqual(3, fromJust(v)) 33 | self.assertEqual(3, fromMaybe(0, v)) 34 | self.assertEqual(4, maybe(0, add1, v)) 35 | 36 | def testNothing(self): 37 | v = Nothing() 38 | self.assertFalse(isJust(v)) 39 | self.assertTrue(isNothing(v)) 40 | with self.assertRaises(AssertionError): 41 | fromJust(v) 42 | self.assertEqual(3, fromMaybe(3, v)) 43 | self.assertEqual(0, maybe(0, add1, v)) 44 | 45 | def testList(self): 46 | lst = [1, 2, 3, 4, 5, 6, 7, 8] 47 | res = mapMaybe(even, lst) 48 | self.assertListEqual(res, [2, 4, 6, 8]) 49 | 50 | def testBindJust(self): 51 | v = Just(4) 52 | vb = v >> even 53 | self.assertTrue(isJust(vb)) 54 | self.assertEqual(4, fromJust(vb)) 55 | 56 | def testBindJust1(self): 57 | v = Just(3) 58 | vb = v >> even 59 | self.assertTrue(isNothing(vb)) 60 | 61 | def testBindNothing(self): 62 | n = Nothing() 63 | nb = n >> even 64 | self.assertTrue(isNothing(nb)) 65 | self.assertIs(n, nb) 66 | 67 | def testNTransJust(self): 68 | v = Just(4) 69 | vforgot = v & forget 70 | self.assertIsInstance(vforgot, Under) 71 | self.assertEqual(vforgot.under(), 4) 72 | 73 | def testNTransNothing(self): 74 | v = Nothing() 75 | vforgot = v & forget 76 | self.assertIsInstance(vforgot, Under) 77 | self.assertIsNone(vforgot.under()) 78 | -------------------------------------------------------------------------------- /fpy/tests/test_parsec.py: -------------------------------------------------------------------------------- 1 | from fpy.parsec.parsec import ( 2 | parser, 3 | one, 4 | neg, 5 | pmaybe, 6 | many, 7 | many1, 8 | ptrans, 9 | peek, 10 | skip, 11 | pseq, 12 | inv, 13 | ) 14 | from fpy.data.either import fromRight 15 | 16 | import unittest 17 | 18 | toks = [1, 2, 3] 19 | 20 | even = lambda x: x % 2 == 0 21 | odd = lambda x: x % 2 != 0 22 | 23 | 24 | class TestParsec(unittest.TestCase): 25 | def testParseOne(self): 26 | p = one(odd) 27 | self.assertTrue(p(toks)) 28 | p = one(even) 29 | self.assertFalse(p(toks)) 30 | 31 | def testParseNeg(self): 32 | p = neg(odd) 33 | self.assertFalse(p(toks)) 34 | p = neg(even) 35 | self.assertTrue(p(toks)) 36 | 37 | def testParseCat(self): 38 | p1 = one(odd) 39 | p2 = one(even) 40 | p = p1 + p2 41 | self.assertTrue(p(toks)) 42 | 43 | def testParseLR(self): 44 | p1 = one(odd) 45 | p2 = one(even) 46 | pl = p1 << p2 47 | pr = p1 >> p2 48 | 49 | self.assertTrue(pl(toks)) 50 | self.assertTrue(pr(toks)) 51 | 52 | def testParseChoice(self): 53 | p1 = one(odd) 54 | p2 = one(even) 55 | p = p1 | p2 56 | self.assertTrue((p + p)(toks)) 57 | 58 | def testMany(self): 59 | p1 = one(odd) 60 | p2 = one(even) 61 | p = many1(p1) 62 | self.assertTrue(p(toks)) 63 | p = many(p2) 64 | self.assertTrue(p(toks)) 65 | 66 | def testSkip(self): 67 | p1 = one(odd) 68 | p2 = one(even) 69 | p = skip(p1) + p2 70 | self.assertTrue(p(toks)) 71 | 72 | def testPSeq(self): 73 | seq = [1, 2, 3] 74 | p = pseq(seq) 75 | self.assertTrue(p(toks)) 76 | self.assertFalse(pseq([2, 3, 4])(toks)) 77 | 78 | def testPeek(self): 79 | p1 = one(odd) 80 | p = peek(p1) 81 | res = p(toks) 82 | self.assertTrue(res) 83 | head, rest = fromRight(None, res) 84 | self.assertEqual(head, [1]) 85 | self.assertIs(toks, rest) 86 | 87 | def testTimeN(self): 88 | p1 = one(odd) 89 | p2 = one(even) 90 | p = p1 | p2 91 | self.assertTrue((p * 2)(toks)) 92 | 93 | def testInv(self): 94 | p1 = pseq("abc") 95 | p2 = inv(p1) 96 | p3 = pseq("cba") 97 | self.assertFalse(p2("abc")) 98 | self.assertTrue((p2 >> p3)("cba")) 99 | -------------------------------------------------------------------------------- /fpy/tests/test_pat.py: -------------------------------------------------------------------------------- 1 | from fpy.experimental.case import case 2 | 3 | import unittest 4 | 5 | class TestCase(unittest.TestCase): 6 | def testConstPat(self): 7 | @case 8 | def test(x): 9 | case(x) 10 | { 1: 1, 11 | 2: 2 } 12 | 13 | self.assertEqual(1, test(1)) 14 | self.assertEqual(2, test(2)) 15 | -------------------------------------------------------------------------------- /fpy/tests/test_state.py: -------------------------------------------------------------------------------- 1 | from fpy.data.state import execState 2 | from fpy.data.state import State, runState, put, get, modify, gets, evalState 3 | from fpy.data.function import const 4 | from fpy.composable.function import func 5 | from fpy.composable.collections import get1 6 | 7 | from fpy.experimental.do import do 8 | from fpy.experimental.case import case 9 | 10 | import unittest 11 | 12 | class TestState(unittest.TestCase): 13 | def testRet(self): 14 | r = runState(State.ret('X'), 1) 15 | self.assertEqual(('X', 1), r) 16 | 17 | def testGet(self): 18 | r = runState(get(), 1) 19 | self.assertEqual((1, 1), r) 20 | 21 | def testPut(self): 22 | r = runState(put(5), 1) 23 | self.assertEqual((None, 5), r) 24 | 25 | def testModify(self): 26 | r = runState(modify(lambda x: x + 1), 1) 27 | self.assertEqual((None, 2), r) 28 | 29 | def testPlay(self): 30 | # Example from: https://wiki.haskell.org/State_Monad 31 | # GameState = (Bool, Int) 32 | def play(chars): 33 | if chars == []: 34 | return gets(get1) >> State.ret 35 | 36 | @func 37 | def case(c, st): 38 | o, s = st 39 | if c == 'a' and o: 40 | return put((o, s + 1)) 41 | elif c == 'b' and o: 42 | return put((o, s - 1)) 43 | elif c == 'c': 44 | return put((not o, s)) 45 | else: 46 | return put((o, s)) 47 | 48 | x, *xs = chars 49 | 50 | return get() >> case(x) >> const(play(xs)) 51 | 52 | r = evalState(play("abcaaacbbcabbab"), (False, 0)) 53 | self.assertEqual(2, r) 54 | 55 | def testDo(self): 56 | @do(State) 57 | def test(): 58 | s <- get() 59 | put(s + 1) 60 | modify(lambda x: x * 2) 61 | 62 | r = execState(test(), 1) 63 | self.assertEqual(4, r) 64 | 65 | def testPlayDo(self): 66 | # Example from: https://wiki.haskell.org/State_Monad 67 | # GameState = (Bool, Int) 68 | @do(State) 69 | def play(chars): 70 | (o, s) <- get() 71 | if chars == []: 72 | return s 73 | 74 | @func 75 | def case(c, o, s): 76 | if c == 'a' and o: 77 | return put((o, s + 1)) 78 | elif c == 'b' and o: 79 | return put((o, s - 1)) 80 | elif c == 'c': 81 | return put((not o, s)) 82 | else: 83 | return put((o, s)) 84 | 85 | x, *xs = chars 86 | 87 | case(x, o, s) 88 | play(xs) 89 | 90 | r = evalState(play("abcaaacbbcabbab"), (False, 0)) 91 | self.assertEqual(2, r) 92 | 93 | def testPlayDoPat(self): 94 | # Example from: https://wiki.haskell.org/State_Monad 95 | # GameState = (Bool, Int) 96 | @do(State) 97 | @case 98 | def play(chars): 99 | (o, s) <- get() 100 | if chars == []: 101 | return s 102 | 103 | x, *xs = chars 104 | 105 | case(x, o, s)({ 106 | ('a', True, _s) : put((o, _s + 1)), 107 | ('b', True, _s) : put((o, _s - 1)), 108 | ('c', _o, _s) : put((not _o, _s)), 109 | _ : put((o, s)) 110 | }) 111 | play(xs) 112 | 113 | r = evalState(play("abcaaacbbcabbab"), (False, 0)) 114 | self.assertEqual(2, r) 115 | -------------------------------------------------------------------------------- /fpy/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Z-Shang/fpy/16463b895dcde8d1b9da7048e795d5084b6e138c/fpy/utils/__init__.py -------------------------------------------------------------------------------- /fpy/utils/placeholder.py: -------------------------------------------------------------------------------- 1 | # poor man's quick lambda 2 | # don't want to do the bytecode tricks lol 3 | 4 | from fpy.composable.function import func 5 | 6 | from typing import TypeVar, Any, Generic, Callable 7 | 8 | T = TypeVar("T") 9 | R = TypeVar("R") 10 | 11 | 12 | class IntermediateFunc(func[R], Generic[R]): 13 | def __init__(self, fn: Callable[[Any], R]): 14 | super().__init__(fn) 15 | 16 | def __eq__(self, a: Any) -> Callable[[Any], bool]: 17 | return lambda x: self(x) == a 18 | 19 | def __ne__(self, a: Any) -> Callable[[Any], bool]: 20 | return lambda x: self(x) != a 21 | 22 | def __add__(self, n: Any) -> Callable[[Any], Any]: 23 | return lambda x: self(x) + n 24 | 25 | def __sub__(self, n: Any) -> Callable[[Any], Any]: 26 | return lambda x: self(x) - n 27 | 28 | def __mul__(self, n: Any) -> Callable[[Any], Any]: 29 | return lambda x: self(x) * n 30 | 31 | def __div__(self, n: Any) -> Callable[[Any], Any]: 32 | return lambda x: self(x) / n 33 | 34 | def __radd__(self, n: Any) -> Callable[[Any], Any]: 35 | return lambda x: n + self(x) 36 | 37 | def __rsub__(self, n: Any) -> Callable[[Any], Any]: 38 | return lambda x: n - self(x) 39 | 40 | def __rmul__(self, n: Any) -> Callable[[Any], Any]: 41 | return lambda x: n * self(x) 42 | 43 | def __rdiv__(self, n: Any) -> Callable[[Any], Any]: 44 | return lambda x: n / self(x) 45 | 46 | def __getattr__(self, *args, **kwargs): 47 | return func(lambda x: self(x).__getattribute__(*args, **kwargs)) 48 | 49 | def __getitem__(self, *args, **kwargs): 50 | return func(lambda x: self(x).__getitem__(*args, **kwargs)) 51 | 52 | def __or__(self, other): 53 | return lambda x: self(x).__or__(other) 54 | 55 | def __hash__(self): 56 | return hash(id(self)) 57 | 58 | 59 | class Placeholder: 60 | def __eq__(self, a: Any) -> Callable[[Any], bool]: 61 | def __f(x: Any) -> bool: 62 | return x == a 63 | 64 | return IntermediateFunc(__f) 65 | 66 | def __ne__(self, a: Any) -> Callable[[Any], bool]: 67 | def __f(x: Any) -> bool: 68 | return x != a 69 | 70 | return IntermediateFunc(__f) 71 | 72 | def __add__(self, n): 73 | return IntermediateFunc(lambda x: x + n) 74 | 75 | def __sub__(self, n): 76 | return IntermediateFunc(lambda x: x - n) 77 | 78 | def __mul__(self, n): 79 | return IntermediateFunc(lambda x: x * n) 80 | 81 | def __div__(self, n): 82 | return IntermediateFunc(lambda x: x / n) 83 | 84 | def __radd__(self, n): 85 | return IntermediateFunc(lambda x: n + x) 86 | 87 | def __rsub__(self, n): 88 | return IntermediateFunc(lambda x: n - x) 89 | 90 | def __rmul__(self, n): 91 | return IntermediateFunc(lambda x: n * x) 92 | 93 | def __rdiv__(self, n): 94 | return IntermediateFunc(lambda x: n / x) 95 | 96 | def __getattr__(self, *args, **kwargs): 97 | return IntermediateFunc(lambda x: x.__getattribute__(*args, **kwargs)) 98 | 99 | def __getitem__(self, *args, **kwargs): 100 | return IntermediateFunc(lambda x: x.__getitem__(*args, **kwargs)) 101 | 102 | def __hash__(self): 103 | return hash(id(self)) 104 | 105 | def __or__(self, other): 106 | return IntermediateFunc(lambda x: x.__or__(other)) 107 | 108 | 109 | __ = Placeholder() 110 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | VERSION = "0.0.18-4" 4 | 5 | DESCRIPTION = "Python module for composing computations" 6 | CLASSIFIERS = [ 7 | "Intended Audience :: Developers", 8 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 9 | "Natural Language :: English", 10 | "Operating System :: OS Independent", 11 | "Programming Language :: Python :: 3", 12 | "Topic :: Software Development :: Libraries :: Python Modules", 13 | ] 14 | 15 | 16 | def main(): 17 | try: 18 | from setuptools import setup 19 | except ImportError: 20 | from distutils.core import setup 21 | 22 | with open("README.md") as fin: 23 | desc = fin.read().strip() 24 | 25 | options = { 26 | "name": "fppy", 27 | "version": VERSION, 28 | "license": "GPLv3", 29 | "description": DESCRIPTION, 30 | "long_description": desc, 31 | "long_description_content_type": "text/markdown", 32 | "url": "https://github.com/Z-Shang/fpy", 33 | "author": "zshang", 34 | "author_email": "z@gilgamesh.me", 35 | "classifiers": CLASSIFIERS, 36 | "packages": [ 37 | "fpy", 38 | "fpy.composable", 39 | "fpy.control", 40 | "fpy.data", 41 | "fpy.debug", 42 | "fpy.experimental", 43 | "fpy.parsec", 44 | "fpy.utils", 45 | "fpy.tests", 46 | ], 47 | "install_requires": ["bytecode"], 48 | } 49 | setup(**options) 50 | 51 | 52 | if __name__ == "__main__": 53 | main() 54 | --------------------------------------------------------------------------------