问题
When trying to understand core.logic throgh the API docs I come across Non-Relational goals and relational goals. I have no idea what this means in practice and why it is important to annotate goals if they are relational or not.
Can you explain with example how the goals are used differently depending on if they are relational or not?
回答1:
In order to explain what non-relational means we need to revisit what relational
means.
If you consider pure functions in functional programming, they always return one value, and for the same input arguments, the same output value is returned.
Say for instance:
f(x) = x + 2
This function always returns 5
for input value 3
.
But there are many situations were functions are inappropriate, as square root, that has 2 results.
sqrt(4) => 2 and -2
Or divide a number by zero, with no results
Seeing a relation as a generalized function, you have:
- Any number of results (zero or more)
- Non deterministic
- in/out arguments can be different for each invocation
- Relationships return true if relation is true and false otherwise.
In order to convert a function to a relation we set the result as a new parameter:
(cons 1 [2]) => [1 2]
(conso 1 [2] [1 2]) => true
But now conso
can be used as a generator if one argument is a variable:
(run 1 [x]
(conso 1 [2] x)) => ([1 2])
(run 1 [x]
(conso 1 x [1 2])) => ([2])
In logic programming the unification answers the question: What the world should look like for this relation to be satisfied?
A non-relational
operator or function is operator that doesn't work as a relation but as a simple function, so unification taking any parameter as variable is not possible.
This happened for instance with operators such as >
and <
before CLP
over finite domains was introduced in namespace clojure.core.logic.fd
.
Many of the concepts here you can find in this talk by Ambrose Bonnaire-Sergeant.
来源:https://stackoverflow.com/questions/33787512/what-does-non-relational-mean-in-practice-for-core-logic