Correct use of findall/3, especially the last result argument - variables

I'm a beginner in Prolog and I am dealing with a problem that might seem stupid to you, but I really can't understand what I'm doing wrong! Ok, I have this file fruits.pl and inside that I have something like this:
fruit(apple,small,sweet).
fruit(lemon,small,nosweet).
fruit(melon,big,sweet).
I have already (inside that file made a coexist(X,Y) atom that checks if two fruits can be put together in a plate. It works fine! But now I can't create a suggest(X) that takes as a parameter a fruit and returns a list of fruits that can be put together in the same plate.
The thing is I was trying to make something like that
suggest(X) :- findall(Y,fruit(Y,_,_), List), coexist(X,Y).
What do you think? Every time I try to run this in swi prolog there is a warning 'singleton variable' and when I press
suggest(apple).
then it says false..
sorry for my english :/

Predicates in Prolog do not return anything. You have goals that are satisfied or not and you can interpret that as returning true or false.
Your predicate suggest(X) should contain another parameter that will be bound to the list of fruits that go together with X. An option would be: suggest(X, List) which describes the following relation: List represents all the fruits that go together with X. Then, you could ask:
?- suggest(apple, List).
List = [pear, cherry].
The goal findall(Y, ... , ...) uses the Y variable internally and Y is still unbound after the goal is satisfied. So, you should move coexist(X,Y) inside the second argument of findall/3 which is the goal that is satisfied in all possible ways. Th rule below works only if X is instantiated (suggest(+X, -List)).
suggest(X, List) :- findall(Y, (fruit(Y,_,_), coexist(X, Y)), List).
You can read this as follows: "List represents all fruits Y that coexist with X".

When you try to define a predicate in Prolog, first of all pretend that you have written that predicate already and start with imagining how you would use it. That is, what queries you would like to pose.
To me, it looks as if coexist/2 already describes what you want. BTW, may_coexist/2 might be a more descriptive name. Why do you want this in a separate list? And why using fruit/3 at all? But for the sake of the question let's assume that this makes sense. So essentially you would have now a relation fruit_compatible/2:
fruit_compatible(F, G) :-
fruit(F, _, _),
may_coexist(F, G),
fruit(G, _, _). % maybe you want to add this?
And now, let's assume you want this list too. So you would have a relation fruit_suggestions/2. How to use it?
?- fruit_suggestions(apple, L).
L = [cherry,pear].
or ... should it be rather L = [pear,cherry]? Or both?
?- fruit_suggestions(lemon, L).
L = [orange].
So every time I want a suggestion I have to think of a fruit. Always thinking: what fruit should it be? Fortunately there is a less demanding way in Prolog: Simply use a variable instead of the fruit! Now we should get all suggestions at once!
?- fruit_suggestions(F, L).
F = apple, L = [cherry, pear]
; F = lemon, L = [orange]
; F = cromulon, L = [embiggy, mushfruit].
So we need to implement it such that it will behave that way. findall/3 alone does not solve this. And implementing it manually is far from trivial. But there is setof/3 which handles variables in exactly that manner. Many of the tiny nitty-gritty design decisions have already been made, like that the list will be sorted ascendingly.
fruit_suggestions(F, L) :-
setof(G, fruit_compatible(F, G), L).
Edit: Due to the discussion below, here would be a solution that also permits empty lists. Note that this sounds trivial but it is not. To see this, consider the query:
?- fruit_suggestions(F, []).
What does it mean? What should F be? Also things that are no fruits at all? In that case we would have to produce solutions for everything. Like F = badger ; F = 42 ; .... Most probably this does not make much sense. What might be intended is those fruits that are incompatible with everything. To this end, we need to add a new rule:
fruit_suggestions(F, []) :-
setof(t,X^Y^fruit(F,X,Y),_),
\+ fruit_compatible(F, _).
fruit_suggestions(F, L) :-
setof(G, fruit_compatible(F, G), L).

Related

Using wolfram to check biconditional involving predicates and quantifiers

I have a habit of trying out correctness about some logical statements with worlfram alpha by generating truth table for them. For example, I can try if this:
((¬x→y)∧(¬x→¬y))→x
is correct or not by geerating truth table for ((¬x→y)∧(¬x→¬y)) which turns out to be the same as x column in the same truth table. Hence the above is correct. However is there any way I can check same for biconditionals involving nested existential and universal quantifiers and predicates? For example can I somehow verify rules of this kind?:
(∀x)(∀y)ϕ(x,y)⇔(∀y)(∀x)ϕ(x,y)
Update
I am able to do following check ∀x,y(x∨y) as follows:
Resolve[ForAll[{x,y}, x or y]]
which correctly returns False as (x∨y) does not hold for all x and y.
So now I thought I can do something similar to obtain True for following (which is a general fact): ¬(∀x)ϕ(x)⇔(∃x)¬ϕ(x). I tried this:
Resolve[ForAll[x,(not ForAll[x, x]) xnor (exists[x,not x])]]
But it did not work. Note that ⇔ is nothing but xnor. So how do I do this especially something like following also correctly returns True:
Resolve[not ForAll[x, x]]
which stands for ¬∀x(x).

Right way to forcibly convert Maybe a to a in Elm, failing clearly for Nothings

Okay, what I really wanted to do is, I have an Array and I want to choose a random element from it. The obvious thing to do is get an integer from a random number generator between 0 and the length minus 1, which I have working already, and then applying Array.get, but that returns a Maybe a. (It appears there's also a package function that does the same thing.) Coming from Haskell, I get the type significance that it's protecting me from the case where my index was out of range, but I have control over the index and don't expect that to happen, so I'd just like to assume I got a Just something and somewhat forcibly convert to a. In Haskell this would be fromJust or, if I was feeling verbose, fromMaybe (error "some message"). How should I do this in Elm?
I found a discussion on the mailing list that seems to be discussing this, but it's been a while and I don't see the function I want in the standard library where the discussion suggests it would be.
Here are some pretty unsatisfying potential solutions I found so far:
Just use withDefault. I do have a default value of a available, but I don't like this as it gives the completely wrong meaning to my code and will probably make debugging harder down the road.
Do some fiddling with ports to interface with Javascript and get an exception thrown there if it's Nothing. I haven't carefully investigated how this works yet, but apparently it's possible. But this just seems to mix up too many dependencies for what would otherwise be simple pure Elm.
(answering my own question)
I found two more-satisfying solutions:
Roll my own partially defined function, which was referenced elsewhere in the linked discussion. But the code kind of feels incomplete this way (I'd hope the compiler would warn me about incomplete pattern matches some day) and the error message is still unclear.
Pattern-match and use Debug.crash if it's a Nothing. This appears similar to Haskell's error and is the solution I'm leaning towards right now.
import Debug
fromJust : Maybe a -> a
fromJust x = case x of
Just y -> y
Nothing -> Debug.crash "error: fromJust Nothing"
(Still, the module name and description also make me hesitate because it doesn't seem like the "right" method intended for my purposes; I want to indicate true programmer error instead of mere debugging.)
Solution
The existence or use of a fromJust or equivalent function is actually code smell and tells you that the API has not been designed correctly. The problem is that you're attempting to make a decision on what to do before you have the information to do it. You can think of this in two cases:
If you know what you're supposed to do with Nothing, then the solution is simple: use withDefault. This will become obvious when you're looking at the right point in your code.
If you don't know what you're supposed to do in the case where you have Nothing, but you still want to make a change, then you need a different way of doing so. Instead of pulling the value out of the Maybe use Maybe.map to change the value while keeping the Maybe. As an example, let's say you're doing the following:
foo : Maybe Int -> Int
foo maybeVal =
let
innerVal = fromJust maybeVal
in
innerVal + 2
Instead, you'll want this:
foo : Maybe Int -> Maybe Int
foo maybeVal =
Maybe.map (\innerVal -> innerVal + 2) maybeVal
Notice that the change you wanted is still done in this case, you've simply not handled the case where you have a Nothing. You can now pass this value up and down the call chain until you've hit a place where it's natural to use withDefault to get rid of the Maybe.
What's happened is that we've separated the concerns of "How do I change this value" and "What do I do when it doesn't exist?". We deal with the former using Maybe.map and the latter with Maybe.withDefault.
Caveat
There are a small number of cases where you simply know that you have a Just value and need to eliminate it using fromJust as you described, but those cases should be few and far between. There's quite a few that actually have a simpler alternative.
Example: Attempting to filter a list and get the value out.
Let's say you have a list of Maybes that you want the values of. A common strategy might be:
foo : List (Maybe a) -> List a
foo hasAnything =
let
onlyHasJustValues = List.filter Maybe.isJust hasAnything
onlyHasRealValues = List.map fromJust onlyHasJustValues
in
onlyHasRealValues
Turns out that even in this case, there are clean ways to avoid fromJust. Most languages with a collection that has a map and a filter have a method to filter using a Maybe built in. Haskell has Maybe.mapMaybe, Scala has flatMap, and Elm has List.filterMap. This transforms your code into:
foo : List (Maybe a) -> List a
foo hasAnything =
let
onlyHasRealValues = List.filterMap (\x -> x) hasAnything
in
onlyHasRealValues

Declare a variable

I didn't touch Prolog since high-school, and even though I've tried to find the info, it didn't help. Below is the example that has to illustrate my problem:
%% everybody():- [dana, cody, bess, abby].
%% Everybody = [dana, cody, bess, abby].
likes(dana, cody).
hates(bess, dana).
hates(cody, abby).
hates(X, Y):- \+ likes(X, Y).
likes_somebody(_, []):- fail.
likes_somebody(X, [girl | others]):-
likes(X, girl) ; likes_somebody(X, others).
likes_everybody(_, []):- true.
likes_everybody(X, [girl | others]):-
likes(X, girl) , likes_everybody(X, others).
maplist(likes_somebody, [dana, cody, bess, abby], [dana, cody, bess, abby]).
How do I declare everybody to just be the list of girls? The commented lines are those which I've tried, but I've got bizarre error messages back.
This is the tutorial I followed more or less so far. I'm using GProlog, if it makes any difference. Sorry for such a basic question. GProlog's manual doesn't deal with language syntax, but I've certainly looked there. As an aside, I would be grateful for information on where to look for language documentation (as opposed to implementation documentation).
Every variable in Prolog must begin with an uppercase letter. So for starters, you want Everybody, not everybody.
Second problem, variables in Prolog are not assignables. So probably what you want to do is make a fact and use that instead:
everybody([dana, cody, bess, abby]).
Your bottom line of code is actually a fact definition and will attempt to overwrite maplist/3. What you probably want to do is put everything above that line into a file (say, called likes.pl) and then consult it ([likes].). Then you can run a query like this:
?- everybody(Everybody), maplist(likes_somebody, Everybody, Everybody).
This won't work, because likes_somebody/2 processes a list in the second argument. The predicate you have for likes_somebody/2 could be written:
likes_somebody(_, []).
but still won't mean much. It simply unifies anything with the empty list:
?- likes_somebody(chicken_tacos, []).
true.
You really need a predicate to tell you if someone is a girl, like this:
girl(dana).
girl(cody).
girl(bess).
girl(abby).
Then you could do what I think you're trying to do, which is something closer to this:
likes_somebody(X) :- girl(X).
Then the maplist construction would work like this:
everybody(Everybody), maplist(likes_somebody, Everybody).
Which would simply return true. You could simplify and eliminate everybody/1 by instead using findall(Girl, girl(X), Everybody) but it's getting weird.
You're trying to do list processing with likes_everybody/2, but it's broken because girl is literally girl, not a variable, and others is literally others, not a list of some kind that could be the tail of another list.
I think you still have some old ideas you need to cleanse. Read some more, write some more, and your code will start to make a lot more sense.

SWI prolog make set of variables name with rbtrees or others means

I have got a term from which I want to get set of variables name.
Eg. input: my_m(aa,b,B,C,max(D,C),D)
output: [B,C,D] (no need to be ordered as order of appearance in input)
(That would call like set_variable_name(Input,Output).)
I can simply get [B,C,D,C,D] from the input, but don't know how to implement set (only one appearance in output). I've tried something like storing in rbtrees but that failed, because of
only_one([],T,T) :- !.
only_one([X|XS],B,C) :- rb_in(X,X,B), !, only_one(XS,B,C).
only_one([X|XS],B,C) :- rb_insert(B,X,X,U), only_one(XS,U,C).
it returns tree with only one node and unification like B=C, C=D.... I think I get it why - because of unification of X while questioning rb_in(..).
So, how to store only once that name of variable? Or is that fundamentally wrong idea because we are using logic programming? If you want to know why I need this, it's because we are asked to implement A* algorithm in Prolog and this is one part of making search space.
You can use sort/2, which also removes duplicates.

Ambiguous grammar?

hi
there is this question in the book that said
Given this grammer
A --> AA | (A) | epsilon
a- what it generates\
b- show that is ambiguous
now the answers that i think of is
a- adjecent paranthesis
b- it generates diffrent parse tree so its abmbiguous and i did a draw showing two scenarios .
is this right or there is a better answer ?
a is almost correct.
Grammar really generates (), ()(), ()()(), … sequences.
But due to second rule it can generate (()), ()((())), etc.
b is not correct.
This grammar is ambiguous due ot immediate left recursion: A → AA.
How to avoid left recursion: one, two.
a) Nearly right...
This grammar generates exactly the set of strings composed of balanced parenthesis. To see why is that so, let's try to make a quick demonstration.
First: Everything that goes out of your grammar is a balanced parenthesis string. Why?, simple induction:
Epsilon is a balanced (empty) parenthesis string.
if A is a balanced parenthesis string, the (A) is also balanced.
if A1 and A2 are balanced, so is A1A2 (I'm using too different identifiers just to make explicit the fact that A -> AA doesn't necessary produces the same for each A).
Second: Every set of balanced string is produced by your grammar. Let's do it by induction on the size of the string.
If the string is zero-sized, it must be Epsilon.
If not, then being N the size of the string and M the length of the shortest prefix that is balanced (note that the rest of the string is also balanced):
If M = N then you can produce that string with (A).
If M < N the you can produce it with A -> AA, the first M characters with the first A and last N - M with the last A.
In either case, you have to produce a string shorter than N characters, so by induction you can do that. QED.
For example: (()())(())
We can generate this string using exactly the idea of the demonstration.
A -> AA -> (A)A -> (AA)A -> ((A)(A))A -> (()())A -> (()())(A) -> (()())((A)) -> (()())(())
b) Of course left and right recursion is enough to say it's ambiguous, but to see why specially this grammar is ambiguous, follow the same idea for the demonstration:
It is ambiguous because you don't need to take the shortest balanced prefix. You could take the longest balanced (or in general any balanced prefix) that is not the size of the string and the demonstration (and generation) would follow the same process.
Ex: (())()()
You can chose A -> AA and generate with the first A the (()) substring, or the (())() substring.
Yes you are right.
That is what ambigious grammar means.
the problem with mbigious grammars is that if you are writing a compiler, and you want to identify each token in certain line of code (or something like that), then ambigiouity wil inerrupt you in identifying as you will have "two explainations" to that line of code.
It sounds like your approach for part B is correct, showing two independent derivations for the same string in the languages defined by the grammar.
However, I think your answer to part A needs a little work. Clearly you can use the second clause recursively to obtain strings like (((((epsilon))))), but there are other types of derivations possible using the first clause and second clause together.