Skip to content

Instantly share code, notes, and snippets.

@Humoud
Created March 21, 2016 07:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Humoud/3ef4575530fb89cbf944 to your computer and use it in GitHub Desktop.
Save Humoud/3ef4575530fb89cbf944 to your computer and use it in GitHub Desktop.
Some notes I gathered on Prolog. Consider this a mini intro to Prolog. Will improve this gist as I continue to learn Prolog.
/*
To run this:
open command prompt execute 'swipl'
then run ['path/to/this/file.pl'].
then query away.
*/
% FACTS
likes(jana, omar).
likes(omar, jana).
likes(jana, farah).
% RULES
dating(X,Y) :-
likes(X,Y),
likes(Y,X).
friendship(X,Y) :-
likes(X,Y);
likes(Y,X).
% notice how ':-' mean IF,
% ';' means OR, and ',' means AND
% Querying is done (in the terminal) the same way facts are declared
% except it will be considered a question and not a fact

Prolog

What is prolog?

Logic declarative programming language. Uses predicate syntax ie. it is similar to natural language.

Programs Used

  • swi-prolog

    • installed:
      brew tap homebrew/x11
      brew install swi-prolog
      
  • swipl compiler (command line)


Facts

What is known. Axioms of an object and its relationship to others.

Example:

  • Dana is fat.
  • The cat is white.
  • Hamad likes Mona.

The predicates are:

  • fat
  • white
  • likes

To convert it to terms which prolog would understand:

Who is fat? fat(dana).

What is white? white(cat).

Who likes who? likes(hamad, mona).

"Arity" = number of parameters passed. the first two are 1, while the last one is 2.

Rules

Rules extend the fact about object and their relationship.

Example:

These are facts
 likes(jana, omar).
 likes(omar, jana).
 likes(jana, farah).

Now we want to know if two persons are dating. We need a Rule. Let's assume that two persons(x,y) are dating if and only if x likes y and y likes x.

Prolog code:

  dating(X,Y) :-
    likes(X,Y),
    likes(Y,X).

Note how X and Y are uppercase letters. In prolog variables should be either uppercase letters of full caps words.

logical prolog operators table

Op syntax
IF :-
NOT not
OR ;
AND ,

Queries

Combines the idea of facts and rules together.

in the terminal:
  likes(khaled, ahmed).
    > false (value returned)
  likes(jana, omar).
    > true (value returned)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment