I have a term contained in a file:
fruit(apple, []).
I'm trying to write input to it, so that each set of information will be appending to the empty list as a list to compose a list of lists, in a manner like:
fruit(apple, [[30, 'fresh'], [10, 'old'], ... ]).
So far I only know how to write a separate term:
add_fruit(File, Type, Price, State) :-
open(File, append, Stream),
writeq(Stream, fruit(Type, [Price, State])),
write(Stream, '.'),
nl(Stream), nl(Stream),
close(Stream).
This will produce a term such as:
fruit(apple, [20, 'some state']).
However I don't want to have to create a new term every time I use the add_fruit predicate, rather I want to append a list containing Price and State to the appropriate fruit type term.
Would it be possible to extend the predicate so that it will write to the existing term, rather than create a new one?
You are mixing up concepts here a bit. First off, if you have a Prolog file, say "food.pl" with the contents:
fruit(apple, []).
then fruit/2 is not exactly a term, but rather the fact fruit/2 (predicate without a body, only with a head) which maps the atom apple (first argument) to the empty list (the second argument).
What you can do now is consult the file, which will put the fact in the database.
Another thing: are you sure you need to keep appending to the list in the second argument? Why not normalize your database, and have, for example:
fruit(apple, price_state(30, fresh)).
fruit(apple, price_state(10, old)).
% etc
Here, you now have a table, fruit, with two columns. The first is the name of the fruit, the second is a term price_state/2 with the price as the first argument and the state as the second. You could have just as well said:
fruit_price_state(apple, 30, fresh).
fruit_price_state(apple, 10, old).
% etc
if you indeed want your table to map the fruit to a state and a price. You can now add and remove rows from the table using assertz and retract. In other words, design your database as you would design a relational database, using facts as tables. This approach translates directly to Prolog. You can then query the database, for example, to give you the combination of price and state for apples:
?- bagof(price_state(P, S), fruit(apple, P, S), PSs).
This will put a list of price_state/2 in PSs, or fail, if you don't have apples in your database (you could use findall/3 if you prefer to get an empty list instead, but then you would have to deal with that empty list in any predicate that takes PSs).
One way to deal with persistence, that is, load facts to the database, add/remove rows, and then save the updated database back to the same file is using Edinburgh-style I/O with see, tell, told etc.
If you are using SWI-Prolog, you also have the option of using library(persistency). See the link for a working minimal example.
Related
My aim is to break the given list of lists in such a way that I am able to access the individual lists by the same name. I have the following list:-
mylist([[1,2],[2,3],[3,4],[4,6]]).
I want to break the list into [1,2], [2,3], [3,4], [4,6] so that I can access the items (like [1,2]) individually.
For that, can I create a new fact from the separated list elements? I am able to separate the elements into individual lists. But, I want to convert those individual lists into facts. Like:-
mylist([[1,2],[2,3],[3,4],[4,6]]).
should become the following:-
node([1,2]).
node([2,3]).
node([3,4]).
node([4,6]).
And then I should be able to access each and every list using "node".
The other answer is fine (esp. the forall solution), but here is what you could do if you knew your list at compile time, and wanted to add the node/1 facts to the database at compile time.
This code is simplified from the example available at the very bottom of this page:
In your file (I will call it nodes.pl):
term_expansion(nodes_list(NL), Nodes) :-
maplist(to_node, NL, Nodes).
to_node(X, node(X)).
nodes_list([[1,2],[2,3],[3,4],[4,6]]).
When I consult the file, I get:
?- [nodes].
true.
?- listing(node).
node([1, 2]).
node([2, 3]).
node([3, 4]).
node([4, 6]).
true.
Two details:
The expanded predicate, here nodes_list/1, is not going to be in the database.
The clause of term_expansion/2 must come before the definition of nodes_list/1 in the source file.
A great answer (maybe the best) recommended(in the comments) by CapelliC is:
?-forall(member(X,[[1,2],[2,3],[3,4]]),assertz(node(X))).
You could also write:
my_list(L):- member(X,L),assertz(node(X)).
Example:
?- my_list([[1,2],[2,3],[3,4]]).
true ;
true ;
true.
?- node([1,2]).
true ;
false.
Another way thanks to CapelliC's recommendation would be:
?- maplist(X>>assertz(node(X)), [[1,2],[2,3],[3,4]]).
I am new to prolog and I am trying to create a predicate and am having some trouble.
I have a list of cities that are connected via train. They are connected via my links/2 clause.
links(toronto, ajax).
links(toronto, markham).
links(toronto, brampton).
links(brampton, markham).
links(markham, ajax).
links(brampton, mississauga).
links(mississauga, toronto).
links(mississuaga, oakville).
links(oakville, st.catharines).
links(oakville, hamilton).
links(hamilton, st.catharines).
I am writing a predicate called addnewcities which will take a list of cities and then return a new list containing the original list, plus all the cities that are directly connected to each of the cities in the original list.
Here is a (rough looking) visual representation of the links.
If my input list was [toronto] I want my output to be (order doesnt matter) [ajax,markham,brampton,mississauga,toronto].
If input was [oakville,hamilton] I want the output to be [mississauga,st.catharines,oakville,hamilton].
Here is my predicate so far.
addnewcities([],_).
addnewcities([CitiesH|Tail],Ans):- directer(CitiesH,Ans2), merger(Ans2,[CitiesH],Ans), addnewcities(Tail,Ans).
directer/2 takes a city and saves a list containing all the directly connected cities in the second arg.
merger/3 just merges two lists making sure there are no duplicates in the final list.
When my input is a list with one element ie [toronto] it works!
But when I have a list with multiple elements [toronto,ajax] it says "false" every time.
I'm pretty sure my issue is that when it recurses for the second time, merge is what says its false. I just don't know how to get around this so that my list can keep being updated instead of being checked if true or false.
Any help is appreciated!
this query uses library support to solve the problem:
addcities(Cs, L) :-
setof(D, C^(member(C,Cs), (C=D;link(C,D);link(D,C))), L).
This should work for what you want:
addcities(A,B):-
addcitiesaux(A,[],B).
addcitiesaux([],X,X).
addcitiesaux([X|Xs],L,R):-
link(X,A),
\+ member(A,L),
!,
addcitiesaux([X|Xs],[A|L],R).
addcitiesaux([X|Xs],L,R):-
link(A,X),
\+ member(A,L),
!,
addcitiesaux([X|Xs],[A|L],R).
addcitiesaux([X|Xs],L,R):-
addcitiesaux(Xs,[X|L],R).
I have a list in prolog that contains several items. I need to 'normalized' the content of this list and write the result to a new list. But I still have problem in doing it.
The following code shows how I did it:
normalizeLists(SourceList, DestList) :-
% get all the member of the source list, one by one
member(Item, SourceList),
% normalize the item
normalizeItem(Item, NormItem),
% add the normalize Item to the Destination List (it was set [] at beginning)
append(NormItem, DestList, DestList).
The problem is in the append predicate. I guess it is because in prolog, I cannot do something like in imperative programming, such as:
DestList = DestList + NormItem,
But how can I do something like that in Prolog? Or if my approach is incorrect, how can I write prolog code to solve this kind of problem.
Any help is really appreciated.
Cheers
Variables in Prolog cannot be modified, once bound by unification. That is a variable is either free or has a definite value (a term, could be another variable). Then append(NormItem, DestList, DestList) will fail for any NormItem that it's not an empty list.
Another problem it's that NormItem it's not a list at all. You can try
normalizeLists([], []).
normalizeLists([Item|Rest], [NormItem|NormRest]) :-
% normalize the item
normalizeItem(Item, NormItem),
normalizeLists(Rest, NormRest).
or (if your Prolog support it) skip altogether such definition, and use an higher order predicate, like maplist
...
maplist(normalizeItem, Items, Normalized),
...
I am attempting to learn the basics of Prolog for a class. I'm running into the seemingly simple problem of not being able to store a list within a rule and retrieve it for usage in other clauses. For example:
% These are the contents of the pl file I want to consult
% Numbers I want to process
inputList([3,2,1,0]).
% Prints out the contents of a list
printList([First | Tail]) :-
write(First),nl,
printList(Tail).
What I want to do is call the following within Prolog:
?- inputList(X).
?- printList(X).
The goal is to avoid constantly entering long lists into the Prolog interpreter and instead store them in the .pl file. However, entering the commands above results in the list not being properly checked against the given clause. How can this be accomplished, preferably using the structure above to store a list {listContents([a,b,c,d]).}?
I think you need to modify your call in Prolog to
?- inputList(X), printList(X).
I have three types of facts:
album(code, artist, title, date).
songs(code, songlist).
musicians(code, list).
Example:
album(123, 'Rolling Stones', 'Beggars Banquet', 1968).
songs(123, ['Sympathy for the Devil', 'Street Fighting Man']).
musicians(123, [[vocals, 'Mick Jagger'], [guitar, 'Keith Richards', 'Brian Jones']].
I need to create these 4 rules:
together(X,Y) This succeeds if X and Y have played on the same album.
artistchain(X,Y) This succeeds if a chain of albums exists from X to Y;
two musicians are linked in the chain by 'together'.
role(X,Y) This succeeds if X had role Y (e.g. guitar) ever.
song(X,Y) This succeeds if artist X recorded song Y.
Any help?
I haven't been able to come up with much but for role(X,Y) I came up with:
role(X,Y) :- prole(X,Y,musicians(_,W)).
prole(X,Y,[[Y|[X|T]]|Z]).
prole(X,Y,[[Y|[H|T]]|Z]) :- prole(X,Y,[[Y|T]|Z]).
prole(X,Y,[A|Z]) :- prole(X,Y,Z).
But that doesn't work. It does work if I manually put in a list instead of musicians(_,W) like [[1,2,3],[4,5,6]].
Is there another way for me to insert the list as a variable?
As for the other rules I'm at a complete loss. Any help would really be appreciated.
You have a misconception about Prolog: Answering a goal in Prolog is not the same as calling a function!
E.g.: You expect that when "role(X,Y) :- prole(X,Y,musicians(_,W))." is executed, "musicians(_,W)" will be evaluated, because it is an argument to "prole". This is not how Prolog works. At each step, it attempts to unify the goal with a stored predicate, and all arguments are treaded either as variables or grounded terms.
The correct way to do it is:
role(X,Y) :- musicians(_, L), prole(X,Y,L).
The first goal unifies L with a list of musicians, and the second goal finds the role (assuming that the rest of your code is correct).
Little Bobby Tables is right, you need to understand the declarative style of Prolog. Your aim is to provide a set of rules that will match against the set of facts in the database.
Very simply, imagine that I have the following database
guitarist(keith).
guitarist(jim).
in_band('Rolling Stones', keith).
in_band('Rolling Stones', mick).
Supposed I want to find out who is both a guitarist and in the Rolling Stones. I could use a rule like this
stones_guitarist(X):-
guitarist(X),
in_band('Rolling Stones', X).
When a variable name is given within a rule (in this case X) it holds its value during the rule, so what we're saying is that the X which is a guitarist must also be the same X that is in a band called 'Rolling Stones'.
There are lots of possible ways for you to arrange the database. For example it might be easier if the names of the musicians were themselves a list (e.g. [guitar,[keith,brian]]).
I hope the following example for song(X,Y) is of some help. I'm using Sicstus Prolog so import the lists library to get 'member', but if you don't have that it's fairly easy to make it yourself.
:- use_module(library(lists)).
song(ARTIST,SONG):-
album(CODE,ARTIST,_,_),
songs(CODE,TRACKS),
member(SONG,TRACKS).