DEV Community

Discussion on: Which programming language/environment is more “powerful” than people realize?

Collapse
 
elmuerte profile image
Michiel Hendriks • Edited

In Prolog you define facts. Like

is_dev('Ben').
fullname('Ben', 'Halpern').
fullname('Michiel', 'Hendriks').

Which you can then query:

?- is_dev(N), fullname(N, 'Halpern')

Which can be "unified" (i.e. a solution) exists. The first answer to the solution is N='Ben'

The facts you define can also be queries.

dev_fullname(FirstName, LastName) :-
    is_dev(FirstName), fullname(FirstName, LastName).

Which allows me to query on either first name or last name like:

?- dev_fullname('Ben', LastName).
LastName = 'Halpern'

?- dev_fullname(FirstName, 'Halpern').
FirstName = 'Ben'

But dev_fullname('Michiel', _) produces no result, because I didn't state the fact I was a dev. (Note, _ is an anonymous variable, which will simply be discarded.

One of the other big features of Prolog is how it handles list.
Below is the typical check if an element is a member of a list:

member(X,[X|_]).
member(X,[_|T]) :- member(X,T).

The first fact says that the result is true if X is the head of the list (second argument).
If the first fact is not true, it will try the second fact. There is queries member again. But drops the head of the list.

Now a fun thing. If you want to iterate over all members of a list. You can use the same fact.

?- member(N,[1,2,3,4,5])

This produces 5 results for N. And if you just want want the numbers higher than 3

?- member(N,[1,2,3,4,5]), N>3

which produces 2 results, N=4 and N=5.