Prolog – Sorting Hat Challenge

hogwarts-sorting-hatProlog is a language built around the Logical Paradigm: a declarative approach to problem-solving.

There are only three basic constructs in Prolog: facts, rules, and queries.

A collection of facts and rules is called a knowledge base (or a database) and Prolog programming is all about writing knowledge bases. That is, Prolog programs simply are knowledge bases, collections of facts and rules which describe some collection of relationships that we find interesting.

So how do we use a Prolog program? By posing queries. That is, by asking questions about the information stored in the knowledge base. The computer will automatically find the answer (either True or False) to our queries.

Source: http://www.learnprolognow.org/

Knowledge Base (Facts & Rules)


Check the following knowledge base used by the Sorting Hat in the Harry Potter story:

/* Facts */
brave(harry).
loyal(harry).
loyal(cedric).
loyal(luna).
fair(harry).
fair(hermione).
patient(cedric).
clever(cedric).
clever(hermione).
curious(luna).

friend(harry,hermione).
friend(harry,ron).
enemy(harry,malfoy).

/* Rules */
belongToGriffindor(X):-brave(X), loyal(X).
belongToGriffindor(X):-friend(harry,X).
belongToHufflepuff(X):-patient(X), loyal(X).
belongToRavenclaw(X):-curious(X).
belongToSlytherin(X):-enemy(harry,X),\+loyal(X).

Note that \+ means NOT

Queries


We can now query this database. For each of the queries listed below, what do you think the computer will return?

True or False Queries:

?-belongToGriffindor(harry).
?-belongToGriffindor(malfoy).
?-belongToGriffindor(hermione).
?-belongToSlytherin(hermione).
?-belongToSlytherin(malfoy).
?-belongToHufflepuff(cedric).

Other Queries:

?-belongToGriffindor(harry).
?-brave(X).
?-fair(X).
?-friend(harry,X).
?-belongToGriffindor(X).
?-belongToSlytherin(X).

Task #1: Try It Online


Test all of the above queries online to see what they return:
https://swish.swi-prolog.org/p/Harry%20Potter%20-%20Sorting%20Hat.pl

Task #2: Griffindor or Ravenclaw?


Can you add a few more facts for a student called “Cho-Chang” who would meet all the requirements to belong to both Griffindor and Ravenclaw.

As a student should only belong to one house, update the rule for belongToRavenclaw() to make sure this rule only returns True for students who are curious but do not already belong to Griffindor.

Extension Task:


Add a few facts and rules to this knowledge base. Create your own queries using the new facts and rules you have added.

Did you like this challenge?

Click on a star to rate it!

Average rating 4.8 / 5. Vote count: 10

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: