Possible to assert a list? - prolog

I would like to ask if it is possible to assert a list instead of singular terms? For example I have tried the following:
assert(user_chosen_fruits([Grapes, Apples, Peaches])).
However, when I queried using user_chosen_fruits(X)., it returns me the following:
X = [_4872, _4878, _4884].
Am I missing out some output processing, or is my assertion simply wrong? I'm not sure if it is even possible to assert lists. Thanks for any help.

You are asserting a list of variables, hence the bindings you get when you call user_chosen_fruits/1. Try instead:
| ?- assertz(user_chosen_fruits(['Grapes', 'Apples', 'Peaches'])).
P.S. The assert/1 predicate is deprecated. Use instead the standard asserta/1 or assertz/1 predicates.

Related

How do I use this Prolog predicate so as to receive the result? Cannot figure out input

Our textbook gave us this example of a structurer for a math equation in Prolog:
math(Result) --> number(Number1), operator(Operator), number(Number2), { Result = [Number1, Operator, Number2] }.
operator('+') --> ['+'].
number('number') --> ['NUMBER'].
I'm quite new to Prolog, however, and I have no idea how to use this example to get the output. I'm under the impression it restructures the input using Result and outputs it for use.
The only input I've tried that doesn't cause an error is math('number', '+', 'number'). but it always outputs false and I don't know why. Furthermore shouldn't it restructure it and give me the result in Result as well?
What should I be inputting here?
This example is a DCG. You should use the phrase/2 interface predicate to access DCGs.
To find out what the DCG describes, start with the most general query, relating the nonterminal math(R) to a list Ls that is described by the first argument:
?- phrase(math(R), Ls).
From the answer you get (very easy exercise!), you will notice that R is probably not what you meant it to be. Hint: Look up (=..)/2.
Notice in particular that you need not be "inputting" anything here: A DCG describes a list. The list can be specified, but need not be given: A variable will do too! Think in terms of relations between arbitrary terms.

In Prolog (SWI), how to build a knowledge base of user supplied pairs and assert to be equal

I am very new to Prolog and trying to learn.
For my program, I would like to have the user provide pairs of strings which are "types of".
For example, user provides at command line the strings "john" and "man". These atoms would be made to be equal, i.e. john(man).
At next prompt, then user provides "man" and "tall", again program asserts these are valid, man(tall).
Then the user could query the program and ask "Is john tall?". Or in Prolog: john(tall) becomes true by transitive property.
I have been able to parse the strings from the user's input and assign them to variables Subject and Object.
I tried a clause (where Subject and Object are different strings):
attribute(Subject, Object) :-
assert(term_to_atom(_ , Subject),
term_to_atom(_ , Object)).
I want to assert the facts that Subject and Object are valid pair. If the user asserts it, then they belong to together. How do I force this equality of the pairs?
What's the best way to go about this?
Questions of this sort have been asked a lot recently (I guess your professors all share notes or something) so a browse through recent history might have been productive for you. This one comes to mind, for instance.
Your code is pretty wide of the mark. This is what you're trying to do:
attribute(Subject, Object) :-
Fact =.. [Object, Subject],
assertz(Fact).
Using it works like this:
?- attribute(man, tall).
true.
?- tall(X).
X = man.
So, here's what you should notice about this code:
We're using =../2, the "univ" operator, to build structures from lists. This is the only way to create a fact from some atoms.
I've swapped subject and object, because doing it the other way is almost certainly not what you want.
The predicate you want is assertz/1 or asserta/1, not assert/2. The a and z on the end just tells Prolog whether you want the fact at the beginning or end of the database.
Based on looking at your code, I think you have a lot of baggage you need to shed to become productive with Prolog.
Prolog predicates do not return values. So assert(term_to_atom(... wasn't even on the right track, because you seemed to think that term_to_atom would "return" a value and it would get substituted into the assert call like in a functional or imperative language. Prolog just plain works completely differently from that.
I'm not sure why you have an empty variable in your term_to_atom predicates. I think you did that to satisfy the predicate's arity, but this predicate is pretty useless unless you have one ground term and one variable.
There is an assert/2, but it doesn't do what you want. It should be clear why assert normally only takes one argument.
Prolog facts should look like property(subject...). It is not easy to construct facts and then query them, which is what you'd have to do using man(tall). What you want to say is that there is a property, being tall, and man satisfies it.
I would strongly recommend you back up and go through some basic Prolog tutorials at this point. If you try to press forward you're only going to get more lost.
Edit: In response to your comment, I'm not sure how general you want to go. In the basic case where you're dealing with a 4-item list with [is,a] in the middle, this is sufficient:
build_fact([Subject,is,a,Object], is_a(Subject, Object)).
If you want to isolate the first and last and create the fact, you have to use univ again:
build_fact([Subject|Rest], Fact) :-
append(PredicateAtoms, [Object], Rest),
atomic_list_concat(PredicateAtoms, '_', Predicate),
Fact =.. [Predicate, Subject, Object].
Not sure if you want to live with the articles ("a", "the") that will wind up on the end though:
?- build_fact([john,could,be,a,man], Fact).
Fact = could_be_a(john, man)
Don't do variable fact heads. Prolog works best when the set of term names is fixed. Instead, make a generic place for storing properties using predefined, static term name, e.g.:
is_a(john, man).
property(man, tall).
property(john, thin).
(think SQL tables in a normal form). Then you can use simple assertz/1 to update the database:
add_property(X, Y) :- assertz(property(X, Y)).

SWI-Prolog goal fail variable binding result

Is there any way that I can get a binding for a variable in Prolog even if the goal fails. I have a predicate where I am binding a variable with some value and after this I am failing the goal explicitly, but when I run the query it simply results in a fail without providing any biding for the variable. Something similar:
a(X) :-
X = 'something',
fail.
#Will Ness is correct (+1), assert can be used to capture bindings of variables as shown.
However, if you strictly need to retrieve bindings for variables in predicates like a and you know which parts could fail (and you don't care about them), then you could use combinations of cut (!) and true to permit a to proceed regardless. For example, consider:
a(X) :-
goalA(X), % a goal for which we definitely want a binding
(goalB, ! ; true). % an 'optional' goal which may fail
goalA('something').
goalB :- fail.
Executing this gives a('something'), even though goalB failed. Note that this isn't a commonly used way to program in Prolog, but if you know exactly what you're doing...
yes, this is how it is supposed to happen in Prolog. fail means the rejection of bindings made so far, because it says that these bindings are invalid, do not satisfy the goal.
but you can save some binding that will be undone on backtracking, with e.g. asserta predicate:
a(X) :-
X = 'something',
asserta(saved_x(X)),
fail.
Then, if you query saved_x(Z) afterwards, you will recover that value. Of course this is the part of Prolog that is extra-logical, i.e. outside of the logical programming paradigm.

How to add to end of list in prolog

I am trying to add one item to the end of a list in prolog, but it keeps on failing.
insertAtEnd(X,[ ],[X]).
insertAtEnd(X,[H|T],[H|Z]) :- insertAtEnd(X,T,Z).
letters([a,b,c]).
I do not understand why this below does not work.
insertAtEnd(d,letters(Stored),letters(Stored)).
I am also attempting to store this list in the variable Stored throughout, but I am not sure if the above is correct way to proceed.
you can use append
and put your item as second list
like this:
insertAtEnd(X,Y,Z) :- append(Y,[X],Z).
Prolog implements a relational computation model, and variables can only be instantiated, not assigned. Try
?- letters(Stored),
insertAtEnd(d, Stored, Updated),
write(Updated).

Correct use of findall/3, especially the first template argument

i know there is a build-in function findall/3 in prolog,
and im trying to find the total numbers of hours(Thrs) and store them in a list, then sum the list up. but it doesnt work for me. here is my code:
totalLecHrs(LN,THrs) :-
lecturer(LN,LId),
findall(Thrs, lectureSegmentHrs(CC,LId,B,E,THrs),L),
sumList(L,Thrs).
could you tell me what's wrong with it? thanks a lot.
You need to use a "dummy" variable for Hours in the findall/3 subgoal. What you wrote uses THrs both as the return value for sumList/2 and as the variable to be listed in L by findall/3. Use X as the first argument of findall and in the corresponding subgoal lectureSegmentHrs/5 as the last argument.
It looks like the problem is that you're using the same variable (Thrs) twice for different things. However it's hard to tell as you've also used different capitalisation in different places. Change the findall line so that the initial variable has the same capitalisation in the lectureSegmentHrs call. Then use a different variable completely to get the final output value (ie the one that appears in sumList and in the return slot of the entire predicate).
You need to use a different variable because Prolog does not support variable reassignment. In a logical language, the notion of reassigning a variable is inherently impossible. Something like the following may seem sensible...
...
X = 10,
X = 11,
...
But you have to remember that , in Prolog is the conjunction operator. You're effectively telling Prolog to find a solution to your problem where X is both 10 and 11 at the same time. So it's obviously going to tell you that that can't be done.
Instead you have to just make up new variable names as you go along. Sometimes this does get a bit annoying but it's just goes with the territory of a logical languages.

Resources