|Just another Perl shrine|
Re: Bringing Logic Programming to Perlby ihb (Deacon)
|on Jan 22, 2005 at 17:08 UTC||Need Help??|
Something my teacher repeatedly say during the lectures was "in logic programming we express relations". Remember this, ponder it, and you'll save yourself some trouble, especially if you already are comfortable with functional languages. Relations are named by predicates and predicates are not functions.
If that is as clear as the sky above the clouds then you can stop reading now. All I'm going to try to do in the rest of this post is to give examples of how these relations work and how they allow you to express programs differently than in other languages that look similar, like Haskell.
A predicate is true if the relation can be true. If there's any uninstantiated variables in the predicate Prolog gives them values that fulfill the relation and keep them for the rest of the scope. This works a bit like capturing groups and backreferences in regexes (like /(.*?)\1/).
An interesting example of this is how the assignment operator = works in Prolog. It's not really an assignment operator. It's a very simple predicate named = and X = Y can be written as =(X, Y). We could've called it eq and written it as
which basically says that the first argument must match the second argument. As you see, it's symmetrical, so X = 2 is the same as 2 = X.
I don't expect anyone without prior knowledge of Prolog to understand the following example, but I think it's nice anyway, and those familiar with functional programming may recognize the example.
If we want to manually define the natural numbers, 0 ... Inf, we can do that by writing an inc predicate used as inc(X, Xplus1) and have a base (atom) just called zero. If we define inc as
the number 2 would be represented by succ(succ(zero)). But here's where the fun comes in. Since predicates express relations we can use it to decrease a value too: inc(Xminus1, X). Here I've said nothing about whether X needs to be instantiated or not. If fact, neither in inc(X1, X2) needs to be instantiated. It just says that after that predicate, X1 and X2 will be two successive numbers:
It's all about relations.
See perltoc if you don't know which perldoc to read!