While Imperative Programming is very common, Logic Programming seems to be not popular at all. Why would anyone use it?
It is an other kind of thinking about problems. There are problems where imperative programming languages, such as C,C++, Java, Python, …, will suck. It is more like making a set of rules/constraints rather than making an algorithm.
The motivation comes from multiple sides:
- Using an other approach to solve problems
- Retry the KI exam (altough my prolog program reached 10 of 10 pts.)
- Science! (No explanation needed)
One who is trapped into imperative programming might fail in thinking about an other approach. Therefore a quick example:
fruit(Apple). fruit(Orange). fruit(Cherry). vegtable(Carrot). vegtable(Spinach). vegtable(Letuce).
This is only a simple knowledgebase which describses some fruits and some vegtables. Now we can ask something like this:
-? fruit(Apple). true. -? vegtable(Apple). false.
One might think “Well, I can do this in <Insert some imperative language> too!”
Which may look like this in pyton:
def fruit(f): return f in ["Apple", "Orange", "Cherry"] def vegtable(v): return v in ["Carrot", "Spinach", "Letuce"]
But how could you figure out all fruits or all vegtables without brute-forcing ?
In Prolog this will (just) look like this
-? fruit(X). X = [Apple, Orange, Cherry] -? vegtables(X). X = [Carrot, Spinach, Letuce]
This doesn’t work in Python unless you make another function. This is because in Prolog Input- and Outputvariables are not fixed. In Python, and all other imperative languages, you have to define what goes in and what goes out.