ZpfSysn
ZpfSysn

Reputation: 889

Prolog Query: Return value based on Facts

I am new to Prolog as a whole and i am learning prolog query.

I am looking at this tutorial. http://www.cs.trincoll.edu/~ram/cpsc352/notes/prolog/factsrules.html and trying to play around with my own database.

Person("Mike", "123456").   //Person(Name,ID)
Info("CA", "123456", "17"). //Info(State, ID, Age)

What I am trying to do:

I am trying to return someone's age by their name and State. by doing the following query, this should return 17.

Age_Of(Name, State, N) :- Info(State, Person(Name, X), N).

i tried the above code and it returns "No". I believe that it is still evaluate as boolean. However, I want the function to return the actual age.

Upvotes: 0

Views: 569

Answers (1)

damianodamiano
damianodamiano

Reputation: 2662

First of all, let's point some facts:

  • You should write your database of facts without using a capital letter as first letter. So Person("Mike", "123456"). should be person("Mike", "123456"). and Info("CA", "123456", "17"). should be info("CA", "123456", "17").
  • In prolog there are not functions but only predicates and should be defined aswell using non capital letter, so Age_Of(Name, State, N) should be age_of(Name, State, N).
  • Even if you remove all first capital letter, you get Singleton variables: [X] while you execute the code. This mean that you dhave defined a variable, in this case X, but not used anywhere. In this case, you should replace every singleton variable with _ or add _ before the variable (_X in this case).

To solve your problem, this is the solution:

person("Mike", "123456").   % person(Name,ID)
info("CA", "123456", "17"). % info(State, ID, Age)


age_of(Name, State, Age):-
   person(Name,ID),
   info(State, ID, Age).

So first you have to find the ID of a person with a given name and then find the corresponding age. Query:

?- age_of(Name,State,Age).
Age = "17",
Name = "Mike",
State = "CA"

This query is quite generic, you can be more specific (for instance, specifing a name). Hope it helps.

Upvotes: 2

Related Questions