4 ms·
Say you want to calculate the area of a triangle, in a Python-style language you would write: def area(base, height): return (base * height) / 2 T
by jodrellblank 6y ago
Say you want to calculate the area of a triangle, in a Python-style language you would write:
def area(base, height):
return (base * height) / 2
This is a function which takes the base and height as inputs, and returns the area as an output, and that is all it can do. You'd never think that's "all" because what else would you expect it to do, but what you wrote down in code? In Prolog, instead you can write this:
:-use_module(library(clpfd)).
triangle_area_sides(Area, Base, Height) :-
Area #= (Base * Height)//2.
This is not a function, it doesn't take any parameters or return anything. It's a rule which says how the Area, Base and Height values are related, and an import for a module which handles numeric calculations. Now you can ask the Prolog rules engine to solve for any missing value(s):
- Given a base and a height, what is the missing Area value? (Same as the Python version)
- Given an Area and a Base, what is the missing Height?
- Given an Area and a Height, what is the missing Base length?
- Given an area, a base and a height, is that a valid triangle?
- Given an Area, generate some / many Base and Height combinations which make a triangle of that area.
- Given a Base, generate some / many Area and Height combinations which make a triangle of that base length.
- Given a Height, generate some / many Area and Base combinations which make a triangle of that height.
- Given nothing, generate some valid triangle sizes.
- Given some values but not others, can it be solved at all (true/false)?
Pros: that's much more capable than the Python function of roughly the same code length. Multiple logic statements like this can make a lot happen in a little code.
Cons: it's very different from imperative programming, it makes IO and state interactions a bit more difficult, it's easy to get the Prolog engine stuck generating infinite combinations or searching enormous search spaces and never finishing, debugging what it's actually doing and what is going wrong is a very different skill from imperative languages.
And years of college courses using Prolog as a "force them to deal with recursion", leaving people with the impression that Prolog is incapable of anything good, and what it can do is slow and needlessly difficult.