0

For my University coursework, I have to write some solutions to PROLOG questions that have been set. They've given us a huge database of facts/predicates, which are articles published by lecturers/researchers at the University. One of the questions asks us to get all the titles that begin with a certain string (which will be told to us when they assess us). I can't work out how I would match part of the title in the predicate.

Here is an example of the predicates:

article('Title 1', 'author1').
article('Title 2', 'author1'). 
article('Title 3', 'author1').
article('Title 4', 'author1').
article('Title 5', 'author2').
article('Title 6', 'author2').

And the code I've tried so far:

findArticlesWith(X,Y) :-
    findall(X,article(match(X,Y),_),Y).

As you can see, the input would be the string to match and then a free variable Y for the list. I am trying to match all the titles that begin with that string, and put them in the list Y. If I queried findArticlesWith('Title',Y). I would want it to return a list of the the titles, e.g Y = ['Title 1', 'Title 2']. etc. However, it just returns an empty list, I assume because there are no titles with just 'Title', instead having something after it.

How do I get the Regex part of Prolog working so it matches for the beginning/end of a string?

Thanks for any help :)

Tom Oakley
  • 6,065
  • 11
  • 44
  • 73
  • Same question asked here: [Prolog wildcard for completing a string](http://stackoverflow.com/questions/27806409/prolog-wildcard-for-completing-a-string) – lurker Jan 07 '15 at 13:58

1 Answers1

0

Your usage of findall is inherently wrong.

You got the last parameter right: the result.

The first parameter describes how a result item is formed. You cannot use X here because X is your search string and already defined. Use something else, Z if you must.

The second parameter specifies the goal that Z has to fulfill: it should be the title of an article and start with X.

Thus, this should work:

findArticlesWith(X,Y) :-
    findall(Z, (article(Z,_), string_concat(X,_,Z)), Y).

but try to find better variable names.

Cephalopod
  • 14,632
  • 7
  • 51
  • 70
  • That's excellent, thank you. Also thanks for explaining `findall` to me, I knew I didn't have it quite right but your explanation makes it clearer. Thanks! – Tom Oakley Jan 07 '15 at 14:09