factorial(0, 1). // it is true that a factorial of 0 is 1
factorial(X, Y) :- // it is true that a factorial of X is Y, when all following are true:
X1 is X - 1, // there is a X1, equal to X - 1,
factorial(X1, Z), // and it is true that factorial of X1 is Z,
Y is Z * X. // and Y is Z * X
I wouldn't say that logic programming defines programs through mathematical expressions; that sounds more like functional programming. Logic programming uses logic expressions (well, eventually logic is math).
当你写一个序言谓词时,你是在定义一个圆号子句:
foo :- bar1, bar2, bar3.表示,如果 bar1、 bar2和 bar3为真,foo 为真。
注意,我没有说 if 和 only if; 可以为一个谓词使用多个子句:
foo:-
bar1.
foo:-
bar2.
意味着如果 bar1为真,或者 bar2为真,foo 为真
Some say that logic programming is a superset of functional programming since each function could be expressed as a predicate:
foo(x,y) -> x+y.
可以写成
foo(X, Y, ReturnValue):-
ReturnValue is X+Y.
但我认为这样的说法有点误导
Another difference between logic and functional is backtracking. In functional programming once you enter the body of the function you cannot fail and move to the next definition. For example you can write
Purity: Haskell is entirely pure, a function Integer -> Integer is a function. No fine print lurking around. And still you can perform side effects. Comparable approaches are very slowly evolving.
The logical append defines a relationship between three lists, which is true if the third list is the elements of the first list followed by the elements of the second list. We think of append as a 断言 that is either true or false for any 3 given lists, and the runtime system is designed to find values that will make this predicate true when we invoke it with some arguments bound to specific lists and some left unbound.