Logic programming in Swift
Logic programming is a declarative style of programming that uses constraints to describe problems. Instead of writing a solution to the problem, you describe the characteristics of the solution and let the computer solve it for you.
Here are some example problems that are a good fit for logic programming:
- Coloring a map/graph so adjacent regions don’t use the same color
- Resolving dependencies in a package manager
- Solving puzzles like sudoku, n-queens, etc.
Different logic programming implementations contain different types of constraints.
Logician is compatible with Swift Package Manager. Add the following line into your
.package(url: "https://github.com/mdiep/Logician.git", .branch("master")
In order to use Logician, you need to be familiar with 3 concepts:
A variable describes an unknown value in a logic problem, much like variables in algebra. Logician variables are generic over a value type.
A goal represents some condition that should be true in the solved state. It’s currently implemented as a
(State) -> Generator<State>. A goal can diverge and return multiple possible states or terminate, signaling that a constraint was violated.
Logician provides a number of built-in goals—like
any—that should provide a good start in most cases.
This function is the interface to Logician’s solver. Its block takes
Variables to solve as input and returns
Goals to solve for.
Logician is still in its early stages. Its current implementation is based on the miniKanren approach of using functions that return generators. This is likely to change in the future in order to enable optimizations.
Logician is available under the MIT License
The following are good resources for learning more about logic programming:
An explanation of how logic programming works in Swift.
μKanren: A Minimal Functional Core for Relational Programming (pdf) by Jason Hemann and Daniel P. Friedman
This paper explores what forms the minimal logic programming language in Scheme. It strips away the complexity of more capable solvers to expose the core idea.
Swift playgrounds with implementations of various Kanrens.
A brief explanation of logic programming and a minimal language in Ruby.
The Reasoned Schemer by Daniel P. Friedman, William E. Byrd and Oleg Kiselyov
An unorthodox book, in the style of The Little Schemer, that has pages of exercises that demonstrate how a kanren-style logic programming works.
Constraint Processing by Rina Dechter
An in-depth look at constraints, algorithms, and optimizations. This book explains all you need to know to write a complex solver.