{"id":21665907,"url":"https://github.com/triska/clpz","last_synced_at":"2026-01-04T11:52:38.817Z","repository":{"id":49762229,"uuid":"56447897","full_name":"triska/clpz","owner":"triska","description":"Constraint Logic Programming over Integers","archived":false,"fork":false,"pushed_at":"2024-02-05T14:19:10.000Z","size":1062,"stargazers_count":172,"open_issues_count":17,"forks_count":14,"subscribers_count":11,"default_branch":"master","last_synced_at":"2024-03-20T03:10:32.263Z","etag":null,"topics":["clp","constraint-programming","constraints","integer-arithmetic","prolog","sicstus-prolog"],"latest_commit_sha":null,"homepage":"https://www.metalevel.at/prolog/clpz","language":"Prolog","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/triska.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-04-17T16:56:55.000Z","updated_at":"2024-03-14T16:10:17.000Z","dependencies_parsed_at":"2024-11-28T07:00:22.339Z","dependency_job_id":null,"html_url":"https://github.com/triska/clpz","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/triska%2Fclpz","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/triska%2Fclpz/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/triska%2Fclpz/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/triska%2Fclpz/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/triska","download_url":"https://codeload.github.com/triska/clpz/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244563630,"owners_count":20472892,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["clp","constraint-programming","constraints","integer-arithmetic","prolog","sicstus-prolog"],"created_at":"2024-11-25T11:18:36.188Z","updated_at":"2026-01-04T11:52:38.763Z","avatar_url":"https://github.com/triska.png","language":"Prolog","funding_links":[],"categories":["Resources"],"sub_categories":["Tutorials"],"readme":"# CLP(ℤ) \u0026mdash; Constraint Logic Programming over Integers\n\nThis repository contains information about **CLP(ℤ)**.\n\nCLP(ℤ) requires **SICStus Prolog**.\n\nAs of April 2020, a version of this library ships with\nScryer\u0026nbsp;Prolog as \u003ctt\u003elibrary(clpz)\u003c/tt\u003e.\n\nThe present implementation builds upon a decade of experience with a\nprecursor library which I developed for a different Prolog system.\nCLP(ℤ) is the *more recent* and conceptually *more advanced*\nimplementation. To keep track of recent developments, use\u0026nbsp;CLP(ℤ).\n\n**Current developments**:\n\n  - increase [**logical purity**](https://www.metalevel.at/prolog/purity) of the implementation\n  - work on *stronger propagation*\n  - *correct* all reported issues.\n  - *add* new constraints.\n\nCLP(ℤ) is being developed for inclusion in\n[**GUPU**](http://www.complang.tuwien.ac.at/ulrich/gupu/).\n\nAn introduction to declarative integer arithmetic is available from\n[**metalevel.at/prolog/clpz**](https://www.metalevel.at/prolog/clpz)\n\n**Video**: https://www.metalevel.at/prolog/videos/integer_arithmetic ![CLP(ℤ) video](figures/t_integer_arithmetic.png)\n\nFor more information about pure Prolog, read [**The Power of Prolog**](https://www.metalevel.at/prolog).\n\n## Using CLP(ℤ) constraints\n\nCLP(ℤ) is an instance of the general CLP(*X*) scheme, extending logic\nprogramming with reasoning over specialised domains.\n\nIn the case of CLP(ℤ), the domain is the set of **integers**. CLP(ℤ)\nis a generalisation of CLP(FD) as provided by SICStus\u0026nbsp;Prolog.\n\nCLP(ℤ) constraints like `(#=)/2`, `(#\\=)/2`, and `(#\u003c)/2` are meant to\nbe used as more general alternatives for lower-level arithmetic\nprimitives over integers. Importantly, they can be used in *all\ndirections*.\n\nFor example, consider a rather typical definition of `n_factorial/2`:\n\n    n_factorial(0, 1).\n    n_factorial(N, F) :-\n            N #\u003e 0,\n            N1 #= N - 1,\n            n_factorial(N1, F1),\n            F #= N * F1.\n\nCLP(ℤ) constraints allow us to quite *freely exchange* the order\nof\u0026nbsp;goals, obtaining for example:\n\n    n_factorial(0, 1).\n    n_factorial(N, F) :-\n            N #\u003e 0,\n            N1 #= N - 1,\n            F #= N * F1,\n            n_factorial(N1, F1).\n\nThis works in all directions, for example:\n\n    ?- n_factorial(47, F).\n    258623241511168180642964355153611979969197632389120000000000 ;\n    false.\n\nand also:\n\n    ?- n_factorial(N, 1).\n    N = 0 ;\n    N = 1 ;\n    false.\n\nand also in the most general case:\n\n    ?- n_factorial(N, F).\n    N = 0,\n    F = 1 ;\n    N = F, F = 1 ;\n    N = F, F = 2 ;\n    N = 3,\n    F = 6 .\n\nThe advantage of using `(#=)/2` to express *arithmetic equality* is\nclear: It is a more general alternative for lower-level predicates.\n\nIn addition to providing declarative integer arithmetic,\nCLP(ℤ)\u0026nbsp;constraints are also often used to solve\n[**combinatorial\u0026nbsp;tasks**](https://www.metalevel.at/prolog/optimization)\nwith\u0026nbsp;Prolog.\n\n## Example programs\n\nThis repository contains several example programs. The main predicates\nare all completely pure and can be used as true relations. This means\nthat you can use the *same* program to:\n\n* *find* a single solution\n* *enumerate* all solutions\n* *complete* partially instantiated solutions\n* *validate* fully instantiated solutions.\n\nTo get an idea of the power, usefulness and scope of CLP(ℤ)\nconstraints, I recommend you work through the examples in the\nfollowing order:\n\n1. [**n_factorial.pl**](n_factorial.pl): Shows how to use CLP(ℤ)\n   constraints for **declarative integer arithmetic**, obtaining very\n   general programs that can be used in all directions. Declarative\n   integer arithmetic is the simplest and most common use of CLP(ℤ)\n   constraints. They are easy to understand and use this way, and\n   often increase generality and logical purity of your code.\n\n2. [**sendmory.pl**](sendmory.pl): A simple cryptoarithmetic puzzle.\n   The task is to assign one of the digits 0,...,9 to each of the\n   letters S,E,N,D,M,O,R and Y in such a way that the following\n   calculation is valid, and no leading zeroes appear:\n\n            S E N D\n          + M O R E\n          ---------\n        = M O N E Y\n\n   This example illustrates several very important concepts:\n\n   * It is the first example that shows **residual constraints** for the\n     most general query. They are equivalent to the original query.\n\n   * It is good practice to separate the **core relation** from\n     `labeling/2`, so that termination and determinism can be observed\n     without an expensive search for concrete solutions.\n\n   * You can use this example to illustrate that the CLP(ℤ) system is able\n     to **propagate** many things that can also be found with human\n     reasoning. For example, due to the nature of the above calculation and\n     the prohibition of leading zeroes, `M` is necessarily 1.\n\n3. [**sudoku.pl**](sudoku.pl): Uses CLP(ℤ) constraints to model and\n   solve a simple and well-known puzzle. This example is well suited\n   for understanding the impact of different **propagation\n   strengths**: Use it to compare `all_different/1` `all_distinct/1`\n   on different puzzles:\n\n   ![](figures/filler.png) ![Sudoku with all_different/1](figures/sudoku_all_different.png) ![](figures/filler20.png) ![Sudoku with all_distinct/1](figures/sudoku_all_distinct.png)\n\n   The small dots in each cell indicate how many elements are pruned\n   by different **consistency techniques**. In many Sudoku puzzles,\n   using `all_distinct/1` makes labeling unnecessary. Does this mean that\n   we can forget `all_different/1` entirely?\n\n   **Video**: https://www.metalevel.at/prolog/videos/sudoku\n\n4. [**magic_square.pl**](magic_square.pl): CLP(ℤ) formulation of [*magic\n   squares*](http://mathworld.wolfram.com/MagicSquare.html). This is a good\n   example to learn about **symmetry breaking** constraints: Consider how\n   you can eliminate solutions that are rotations, reflections etc. of\n   other solutions, by imposing suitable further constraints. For example,\n   the following two solutions are essentially identical, since one can be\n   obtained from the other by reflecting elements along the main diagonal:\n\n   ![](figures/filler.png) ![Magic square solution](figures/magic_square1.png) ![](figures/filler20.png) ![Magic square transposed](figures/magic_square2.png)\n\n   Can you impose additional constraints so that you get only a single\n   solution in such cases, without losing any solutions that do not\n   belong to the same equivalence class? How many solutions are there\n   for N=4 that are unique up to isomorphism?\n\n5. [**magic_hexagon.pl**](magic_hexagon.pl): Uses CLP(ℤ) to describe a\n   [*magic hexagon*](http://mathworld.wolfram.com/MagicHexagon.html) of\n   order 3. The task is to place the integers 1,...,19 in the following\n   grid so that the sum of all numbers in a straight line (there are lines\n   of length 3, 4 and 5) is equal to 38. One solution of this task is shown\n   in the right picture:\n\n   ![](figures/filler.png) ![Magic hexagon grid](figures/magic_hexagon.png) ![](figures/filler20.png) ![Magic hexagon solution](figures/magic_hexagon_solution.png)\n\n   This is an example of a task that looks very simple at first, yet\n   is almost impossibly hard to solve manually. It is easy to solve\n   with CLP(ℤ) constraints though. Use the constraint solver to show\n   that the solution of this task is unique up to isomorphism.\n\n6. [**n_queens.pl**](n_queens.pl): Model the so-called [*N-queens\n   puzzle*](https://en.wikipedia.org/wiki/Eight_queens_puzzle) with\n   CLP(ℤ) constraints. This example is a good candidate to experiment\n   with different **search strategies**, specified as options of\n   `labeling/2`. For example, using the labeling strategy `ff`, you\n   can easliy find solutions for 100 queens and more. Sample solutions\n   for 8 and 50 queens:\n\n   ![](figures/filler.png) ![Solution for 8 queens](figures/queens8_solution.png) ![](figures/filler20.png) ![Solution for 50 queens](figures/queens50_solution.png)\n\n   Try to find solutions for larger N. Reorder the variables so that\n   `ff` breaks ties by selecting more central variables first.\n\n   **Video**: https://www.metalevel.at/prolog/videos/n_queens\n\n7. [**knight_tour.pl**](knight_tour.pl): Closed Knight's Tour using\n   CLP(ℤ) constraints. This is an example of using a more complex\n   **global constraint** called `circuit/1`. It shows how a problem\n   can be transformed so that it can be expressed with a global\n   constraint. Sample solutions, using an 8x8 and a 16x16 board:\n\n   ![](figures/filler.png) ![Closed knight's tour on an 8x8 board](figures/knight8_solution.png) ![](figures/filler20.png) ![Closed knight's tour on a 16x16 board](figures/knight16_solution.png)\n\n   Decide whether `circuit/1` can also be used to model tours that are\n   not necessarily closed. If not, why not? If possible, do it.\n\n8. [**tasks.pl**](tasks.pl): A task scheduling example, using the\n   `cumulative/2` global constraint. The `min/1` labeling option is\n   used to minimize the total duration.\n\n   ![](figures/filler.png) ![Task scheduling](figures/tasks.png)\n\n## Animations\n\nWhen studying Prolog and CLP(ℤ) constraints, it is often very useful\nto show *animations* of search processes. An instructional example:\n\n[**N-queens animation**](https://www.metalevel.at/queens/): This\nvisualizes the search process for the N-queens example.\n\nYou can use similar PostScript instructions to create [custom\nanimations](https://www.metalevel.at/postscript/animations) for\nother examples.\n\n## A limited alternative: Low-level integer arithmetic\n\nSuppose for a moment that CLP(ℤ) constraints were not available in\nyour Prolog system, or that you do not want to use them. How do we\nformulate `n_factorial/2` with more primitive integer arithmetic?\n\nIn our first attempt, we simply replace the declarative CLP(ℤ)\nconstraints by lower-level arithmetic predicates and obtain:\n\n    n_factorial(0, 1).\n    n_factorial(N, F) :-\n            N \u003e 0,\n            N1 is N - 1,\n            F is N * F1,\n            n_factorial(N1, F1).\n\nUnfortunately, this does not work at all, because lower-level\narithmetic predicates are *moded*: This means that their arguments\nmust be sufficiently instantiated at the time they are invoked.\nTherefore, we must reorder the goals and\u0026nbsp;\u0026mdash; somewhat\nannoyingly\u0026nbsp;\u0026mdash; change this for example to:\n\n    n_factorial(0, 1).\n    n_factorial(N, F) :-\n            N \u003e 0,\n            N1 is N - 1,\n            n_factorial(N1, F1),\n            F is N * F1.\n\nNaive example queries inspired more by *functional* than by\n*relational* thinking may easily mislead us into believing that this\nversion is working correctly:\n\n    ?- n_factorial(6, F).\n    F = 720 ;\n    false.\n\nAnother example:\n\n    ?- n_factorial(3, F).\n    F = 6 ;\n    false.\n\nBut what about *more general* queries? For example:\n\n    ?- n_factorial(N, F).\n    N = 0,\n    F = 1 ;\n    ERROR: n_factorial/2: Arguments are not sufficiently instantiated\n\nUnfortunately, this version thus cannot be directly used to enumerate\nmore than one solution, which is another severe drawback in comparison\nwith the more general version.\n\nYou can make the deficiency a lot worse by arbitrarily adding\na\u0026nbsp;`!/0` somewhere. Using `!/0` is a quite reliable way to destroy\nalmost all declarative properties of your code in most cases, and this\nexample is no exception:\n\n    n_factorial(0, 1) :- !.\n    n_factorial(N, F) :-\n            N \u003e 0,\n            N1 is N - 1,\n            n_factorial(N1, F1),\n            F is N * F1.\n\nThis version appears in several places. The fact that the following\ninteraction *incorrectly* tells us that there is exactly one solution of\nthe factorial relation is apparently no cause for concern there:\n\n    ?- n_factorial(N, F).\n    N = 0,\n    F = 1.\n\nZero and one are the only important integers in any case, if you are\nmostly interested in programming at a very low level.\n\nFor more usable and general programs, I therefore recommend you stick\nto CLP(ℤ) constraints for integer arithmetic. You can place pure\ngoals in any order without changing the declarative meaning of your\nprogram, just as you would expect from logical conjunction. For\nexample:\n\n    n_factorial(0, 1).\n    n_factorial(N, F) :-\n            N #\u003e 0,\n            N1 #= N - 1,\n            n_factorial(N1, F1),\n            F #= N * F1.\n\nReordering pure goals can change **termination properties**, but it\ncannot incorrectly lead to failure where there is in fact a solution.\nTherefore, we get with the above CLP(ℤ) version for example:\n\n    ?- n_factorial(N, 3).\n    \u003cloops\u003e\n\nAnd now we can reason completely declaratively about the code: Knowing\nthat (a)\u0026nbsp;CLP(ℤ) constraints are *pure* and can thus be reordered\nquite liberally and (b)\u0026nbsp;that posting CLP(ℤ) constraints *always\nterminates*, we *know* that placing CLP(ℤ) constraints earlier can at\nmost *improve*, never *worsen* the desirable termination properties.\n\nTherefore, we change the definition to the version shown initially:\n\n    n_factorial(0, 1).\n    n_factorial(N, F) :-\n            N #\u003e 0,\n            N1 #= N - 1,\n            F #= N * F1,\n            n_factorial(N1, F1).\n\nThe sample query now terminates:\n\n    ?- n_factorial(N, 3).\n    false.\n\nUsing CLP(ℤ) constraints has allowed us to improve the termination\nproperties of this predicate by purely declarative reasoning.\n\n## Acknowledgments\n\nI am extremely grateful to:\n\n[**Ulrich Neumerkel**](http://www.complang.tuwien.ac.at/ulrich/), who\nintroduced me to constraint logic programming.\n\n[**Nysret Musliu**](http://dbai.tuwien.ac.at/staff/musliu/), my thesis\nadvisor, whose interest in combinatorial tasks and constraint\nsatisfaction highly motivated me to work in this area.\n\n[**Mats Carlsson**](https://www.sics.se/~matsc/), the designer and\nmain implementor of SICStus Prolog and its superb [CLP(FD)\nlibrary](https://sicstus.sics.se/sicstus/docs/latest4/html/sicstus.html/lib_002dclpfd.html#lib_002dclpfd)\nwhich spawned my interest in constraints.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftriska%2Fclpz","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftriska%2Fclpz","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftriska%2Fclpz/lists"}