Operations on lists in Prolog - list

I'm new to Prolog and what I want to achieve is to perform an operation like append/3 over two lists that are saved in my program. I don't need to open swi-prolog and type append([a,b,c],[h,j,k],X). in order to obtain X=[a,b,c,h,j,k]. What I need is something like retrieve two lists from the program and perform the append over them.
I don't even know if what I want to obtain is possible in Prolog.
This is my situation: I got this "esempio.pl" file where I have the following rule and these two facts:
personal_union(F,C,Xs) :-
personal_list(F,Fs),personal_list(C,Cs),append(Fs,Cs,Xs).
personal_list(family,[alessandro,cinzia,fabio]).
personal_list(colors,[blu,giallo,lilla,verde,rosso]).
I'd like to question "esempio.pl" from SWI-prolog and ask it:
personal_union(family,colors,X).
And obtain the unified lists:
X=[alessandro,cinzia,fabio,blu,giallo,lilla,verde,rosso]`
Is my code a possible solution? I couldn't try it myself because it keeps giving me this error: Syntax error: illegal start of term stating that the error is at the start of the body of my rule.

Your code is valid as I tested it on Swish, and it produces the requested result.
The error you get is usually derived of mistaken syntax such as additional commas or brackets issues. Check the rest of you code. Also, you might find http://swish.swi-prolog.org/ comfortable for such debugging.

Related

Assign variable in list

I've got a problem with Prolog lists.
Let's say I've got this predicate:
array(p, [A,B,C]).
When I do:
array(p,X).
I got: X = [_,_,_]
Now, considering I've got this predicate:
p1(1) :- array(p1, [1,B1,C1]).
I expected to get:
X = [1,_,_]
but instead, the result is the same as before. Is such a thing even possible in Prolog? Another question is if somehow we can set these values, could we overwrite these values in the same way? I understand that in the prolog variables are assigned only once but I would like to somehow get a dynamic list.
I'm not sure what you mean by "paradigm," and I'm very unclear on what you're trying to do with this code. If you have this at the toplevel:
array(p, [A,B,C]).
you are defining a fact array/2, which associates p with a list of three uninstantiated variables. Your first query amounts to retrieving this fact.
Your second "paradigm" is really the definition of a rule or predicate p1/1, which takes a single argument, which must be 1 for the rule to fire. The body of this second predicate is a call to the predicate array/2 which is definitely going to fail. I don't see how you could possibly get the same result as before, because you defined array(p, ...) before and now you are looking for array(p1, ...). Furthermore, there is no X in your second query, so there is no reason for X to appear in the result, and it definitely would not, even if you had called array(p, ...) instead of array(p1, ...).
I think what you're trying to do here is probably set up some kind of set of three variables and then unify each of them in turn as you proceed along some calculation. To do something like that is possible and easy in Prolog, but the fact database is not going to participate in this process really. You're going to have to write predicates that pass your variables along to other predicates that will unify them and return them bound. None of this is very hard, but it looks like you're going to have to go back and understand the fundamentals here a little better. You're far enough off track here that I don't think anyone can really answer your question as stated, because there's too much confusion in it.

Prolog if then with negated condition

I have a complex program, a part of which looks somewhat like this:
check_list([]).
check_list([X|List]) :- (try_something(X) -> write(1);write(0)),nl,check_list(List).
The problem is that, when my list gets very large, Prolog gives me "Resource error: insufficient memory". I thought the problem might be somewhere in the if-then-clause. So I tried the following:
check_list([]).
check_list([X|List]) :- (\+try_something(X) -> write(0);write(1)),nl,check_list(List).
With that, the problem is gone (or at least it only appears with much much bigger lists). However, I have no clue why. What is so different in the two versions? Shouldn't both be the same?

searching in list getting true infinitely in prolog

I tried to code a Prolog program that takes 2 value and calculates if the pair is valid or not. If pairs are in different lists, then pairs will be valid and they can make match. If two team in same list(group) then they can't make match which means false.
when i started the program it doesn't show anything. I thought there would be infinite searching or looping. Then tried that simple code
GroupB=[china,usa,chile,italy].
member(X,[X|_]).
member(X,[_|T]):-
member(X,T).
match(X):-
member(X,GroupB).
In that code i saw that program always gives me true. I typed; to SWI-Prolog it gave me another true, i typed ; again another true then i realized that the problem should be in that searching part. Thanks for all interests from now. All suggestions are welcome.
edit:
I edited the code like that to try a different style
GroupA([germany,brazil,turkey,korea]).
GroupB([china,usa,chile,italy]).
member(X,[X|_]).
member(X,[_|T]):-
member(X,T).
memberence(X):-
GroupA(L).
GroupB(M).
member(X,L).
member(X,M).
collision(X,Y):-
GroupA(L),
member(X,L),
member(Y,L).
GroupB(L),
member(X,L),
member(Y,L).
match(X,Y) :-
GroupA(L),
memberence(X),
memberence(Y),
\+collision(X,Y).
now i got:
ERROR: Undefined procedure: match/2
ERROR: However, there are definitions for:
ERROR: catch/3
although there is a match(X,Y) procedure why it gives me undefined match/2 error.
GroupA=[germany,brazil,turkey,korea].
GroupB=[china,usa,chile,italy].
member(X,[X|_]).
member(X,[_|T]):-
member(X,T).
memberence(X):-
member(X,GroupA).
member(X,GroupB).
collision(X,Y):-
member(X,GroupA),
member(Y,GroupA).
member(X,GroupB),
member(Y,GroupB).
match(X,Y) :-
memberence(X),
memberence(Y),
\+collision(X,Y).
a)
You have a dot that must be comma in:
collision(X,Y):-
member(X,GroupA),member(Y,GroupA).
member(X,GroupB),member(Y,GroupB).
b)
Better you do not redefine "member", it is standard.
c)
If I change dot by comma in:
collision(X,Y):-
GroupA(L),member(X,L),member(Y,L),
GroupB(L),member(X,L),member(Y,L).
this statement will fail always because there are no list "L" common to GroupA and GroupB.
d)
If we take what seems the original request "takes 2 value and calculates if the pair is valid or not. If pairs are in different lists, then pairs will be valid and they can make match. If two team in same list(group) then they can't make match which means false."
the solution seems obvious:
match(X,Y) :- groupA(A), member(X,A), groupB(B), member(Y,B).
match(Y,X) :- groupA(A), member(X,A), groupB(B), member(Y,B).
You have 2 big problems.
First, you seem to use . and , interchangeably.
Second, you fail to understand Prolog's scoping rules. Anything that isn't asserted into the prolog database is scoped to the immediate statement or the clause of the predicate of which is a part. If you want somebody to know about it, it either has to be a part of the prolog database or passed as an argument. Thus, when you say something like
GroupB = [china,usa,chile,italy].
The variable GroupB Is unified with the list [china,usa,chile,italy]. At which point, the assertion succeeds, and both the newly-bound variable and the list with which it was unified ** go out of scope** and cease to exist. Then, when you attempt to reference it later on:
GroupB=[china,usa,chile,italy].
.
.
.
match(X) :- member(X,GroupB).
The variable GroupB is unbound. Your implementation of member/2,
GroupB=[china,usa,chile,
member(X,[X|_]) .
member(X,[_|T]) :- member(X,T) .
is more than willing to act in a generative manner when given an unbound variable as its 2nd argument, generating lists of variable, successively (and infinitely) longer on backtracking.

Matlab coder build error when trying to access structures

I have a nested structure with some fields labeled as L1, L2 etc. I try to access a substructure within the structure using the following code.
lfield = lfidcalc(le);
substruct = bmstruct.(lfield);
Since le changes its value in every iteration, lfield also changes its value from L1 to L9.
However, when I try to build this code to generate a C++ executable, I get the following error.
Non-constant expression or empty matrix. This expression must be
constant because its value determines the size or class of some
expression. In this context, the value of the string must be known.
Can anybody please try to help me sort out this problem?
I'm not sure exactly what's causing the error message you're seeing, but in any case MATLAB Coder does not support accessing the fields of a structure using dynamic field names.
Perhaps that is the direct cause of what you're seeing, perhaps not: but in either case you have a problem.
Not all correct matlab code can be converted to C/C++. Especially this kind of (very handy) code. Have you put '%#eml' on the second line of your function? It indicates that you will generate code. From matlab website: " We use the %#eml directive to turn on the MATLAB M-Lint code analyzer and check the function code for errors and recommend corrections."

calculating user defined formulas (with c++)

We would like to have user defined formulas in our c++ program.
e.g. The value v = x + ( y - (z - 2)) / 2. Later in the program the user would define x,y and z -> the program should return the result of the calculation. Somewhen later the formula may get changed, so the next time the program should parse the formula and add the new values. Any ideas / hints how to do something like this ? So far I just came to the solution to write a parser to calculate these formulas - maybe any ideas about that ?
If it will be used frequently and if it will be extended in the future, I would almost recommend adding either Python or Lua into your code. Lua is a very lightweight scripting language which you can hook into and provide new functions, operators etc. If you want to do more robust and complicated things, use Python instead.
You can represent your formula as a tree of operations and sub-expressions. You may want to define types or constants for Operation types and Variables.
You can then easily enough write a method that recurses through the tree, applying the appropriate operations to whatever values you pass in.
Building your own parser for this should be a straight-forward operation:
) convert the equation from infix to postfix notation (a typical compsci assignment) (I'd use a stack)
) wait to get the values you want
) pop the stack of infix items, dropping the value for the variable in where needed
) display results
Using Spirit (for example) to parse (and the 'semantic actions' it provides to construct an expression tree that you can then manipulate, e.g., evaluate) seems like quite a simple solution. You can find a grammar for arithmetic expressions there for example, if needed... (it's quite simple to come up with your own).
Note: Spirit is very simple to learn, and quite adapted for such tasks.
There's generally two ways of doing it, with three possible implementations:
as you've touched on yourself, a library to evaluate formulas
compiling the formula into code
The second option here is usually done either by compiling something that can be loaded in as a kind of plugin, or it can be compiled into a separate program that is then invoked and produces the necessary output.
For C++ I would guess that a library for evaluation would probably exist somewhere so that's where I would start.
If you want to write your own, search for "formal automata" and/or "finite state machine grammar"
In general what you will do is parse the string, pushing characters on a stack as you go. Then start popping the characters off and perform tasks based on what is popped. It's easier to code if you force equations to reverse-polish notation.
To make your life easier, I think getting this kind of input is best done through a GUI where users are restricted in what they can type in.
If you plan on doing it from the command line (that is the impression I get from your post), then you should probably define a strict set of allowable inputs (e.g. only single letter variables, no whitespace, and only certain mathematical symbols: ()+-*/ etc.).
Then, you will need to:
Read in the input char array
Parse it in order to build up a list of variables and actions
Carry out those actions - in BOMDAS order
With ANTLR you can create a parser/compiler that will interpret the user input, then execute the calculations using the Visitor pattern. A good example is here, but it is in C#. You should be able to adapt it quickly to your needs and remain using C++ as your development platform.