Prolog reassigning operators - prolog

I'm new to prolog and I'm trying to reassign operators in prolog by changing their precedence. I'm running into 4 errors for the following:
:-op(1000,yf,+). %unary plus%
:-op(1000,yf,-). %unary minus%
:-op(750,yfx,"%"). %modulo%
The first two give me a similar error that goes like this:
warning: directive failed (op(1000,xf,+)) with exception (error(permission_error(create,operator,+),op/3))
I also get an error with the modulo one (a different error), but I suspect it's because I'm not supposed to enclose % in quotes (but how am I supposed to differentiate it from a comment marker?).
I've redefined a bunch of other operators (such as the addition operator :-op(500,yfx,+).) and they give me no problems. Only the 3 listed above give me errors.
Can anyone shed some light on this?
Thanks!

GNU Prolog documentation states that
An atom can have multiple operator definitions (e.g. prefix and infix like +) however an atom cannot have both an infix and a postfix operator definitions.
from here the errors on first two declaration. Then you should change the specifier to fy.
The modulo operator will need single quotes around.

You are attempting to define + as a postfix operator. However, + is also defined as an infix operator and the standard does not permit to define an operator both as postfix and infix. If you really want to do this you have to first undefine the infix operator using priority 0.
However, I can only recommend that you do not change standard operators like + or -. It's like you would change the operator precedence in C, C++, C#, Java, Perl, PHP, Javascript and the like: It would make your life as a programmer very, very miserable.
I cannot recommend to use % as operator in Prolog: % starts a comment. If you want to use it as an operator, you would have to write '%' quoted all the time. Prolog has already mod and rem defined as operators. Isn't that enough?
You are probably using GNU Prolog which is quite ISO conforming. Other Prologs permit you to define infix and postfix at the same time. See #237. But those other Prologs do a lot of things differently.
As a general remark: As a beginner, better stay away from changing the operator table. You really need to get used to the standard operators first. And with more experience you will most probably prefer to only add new operators with similar precedence than existing ones.
iso-prolog: ISO/IEC 13211-1:1995 6.3.4.3 Operators, last paragraph:
There shall not be an infix and a postfix operator with thesame name.

Related

Creating a if else in prolog

I'm trying to create a if/else verification in prolog, but actually i cant pass a parenthesis as a predicate "parameter", the code follows bellow
s(Z):- si(X), vp(Y), append(X,Y,Z).
si(Z):- i(X), openParent(Y), append(X,Y,Z).
vp(Z):- cond(X), closeParent(Y), append(X,Y,Z).
i([if]).
openParent(['(']).
closeParent([')']).
cond([cond]).
%running s(X) to see all the possibilities:
%expected : if, (, cond, )
%output : if, '(', cond, ')'
On openParent and closeParent i want to pass the parenthesis without quotes, but if do, the execution gives an error.
Prolog constants start with lower case letters, if you want to have constants that do not follow this convention you have to escape them via '('. To distinguish them from the reserved keywords the escaping needs to stay in place. This is still better than C for example, where int void = 0 is a forbidden statement and there's no escaping to write it down.
You might also want to think about what your predicate is supposed to do. A unary predicate like s/1 can only tell you if the term you pass fulfils your requirements. If you want to create something out of it (for example an evaluation of the if-then-else) you would need two arguments s(Ast, Evaluation).
Another observation is that you are already working on a symbolic representation: your code produces e.g. a list [if, '(', Cond, ')', TrueBranch] where if only takes one space (a string would use two). But if the representation is symbolic, why not just represent parenthesis as lparen and rparen? Or even better, if has only two / three arguments, why not represent it as if(Cond, TrueBranch) and if(Cond, TrueBranch, ElseBranch)?

What does the "%" mean in tcl?

In a situation like this for example:
[% $create_port %]
or [list [% $RTL_LIST %]]
I realized it had to do with the brackets, but what confuses me is that sometimes it is used with the brackets and variable followed, and sometimes you have brackets with variables inside without the %.
So i'm not sure what it is used for.
Any help is appreciated.
% is not a metacharacter in the Tcl language core, but it still has a few meanings in Tcl. In particular, it's the modulus operator in expr and a substitution field specifier in format, scan, clock format and clock scan. (It's also the default prompt character, and I have a trivial pass-through % command in my ~/.tclshrc to make cut-n-pasting code easier, but nobody else in the world needs to follow my lead there!)
But the code you have written does not appear to be any of those (because it would be a syntax error in all of the commands I've mentioned). It looks like it is some sort of directive processing scheme (with the special sequences being [% and %], with the brackets) though not one I recognise such as doctools or rivet. Because a program that embeds a Tcl interpreter could do an arbitrary transformation to scripts before executing them, it's extremely difficult to guess what it might really be.

Coq notation format for double square braces

According to the documentation, one can define formats for printing notations:
https://coq.inria.fr/refman/Reference-Manual014.html#sec530
However, one can define a notation such as:
Notation " '[[' a ']]' b " := (* something *).
It is very unclear whether the two can interact. Trying:
format " '[hv' '[[' a ']]' ']' b "
for instance, trips Coq up as it expects a square brace to be followed by one of , v, and hv.
Any other sort of escaping I have tried so far made Coq refuse the format as not matching the notation.
I'm not sure this can be done...
Your friend here is metasyntax:parse_format https://github.com/coq/coq/blob/trunk/toplevel/metasyntax.ml#L102
As you can see in the code, your concrete scheme is not going to work. I dunno if there could be some specific hack, for now you'll have to desist using double brackets.
I am certain however that a patch adding a case for [[ in parse_quoted would be considered by Coq upstream.
Hopefully 8.7 will bring some improvements here, CEP#9 tries to propose replacing/evolving unparsing to a true box-based model.

Extract function names from function calls in C files

Is it posible to extract function calls in C source files, e.g.,
...
myfunc(1);
...
or
...
myfunc(anotherfunc(1, 2));
....
by just using Ruby regular expression? If not, would a parser generator such as ANTLR be useful?
This is not a full-proof pattern for finding out method calls but should just serve the pattern that you are interested in.
[a-zA-Z\s]*\([a-zA-Z0-9]*(\([a-zA-Z0-9\s]*[\s,]*[\sa-zA-Z0-9]*\))?\);
This regex will match following method call patterns.
1. myfunc(another(one,two));
2. myfunc();
3. myfunc(another());
4. myfunc(oneArg);
You can also use the regular expressions already written from grammar that are used by emacs -- imenu , etags, ecb, c-mode etc.
In the purest sense you can't, because the possibility to nest function calls recursively makes it a non-regular language. That is, you cannot write a regular expression that matches an arbitrary function call and extracts all of the contained function names.
But of course you could search incrementally for sequences of characters allowed in function names (ie., must start with a letter or underscore, followed by letters, underscore, numbers, etc...) followed by an left parenthesis, or something along those lines.
Keep in mind, however, that any such approach is prone to errors: what if a function is referenced in a comment? What if it appears inside a string constant? Really, to catch all the special cases you would have to (almost) properly parse the full C file.
Most modern regular expression engines have features to parse more than regular languages e.g. by means of back-references to subexpressions. But you shouldn't go down that road. With a proper parser such as ANTLR that can parse context-free languages you'll make your own life a lot easier.

Write a code to generate the parse tree

This question was asked to me in an interview question:
Write a code to generate the parse tree like compilers do internally for any given expression. For example:
a+(b+c*(e/f)+d)*g
Start by defining the language. No one can implement a parser or a compiler to a language that isn't very well defined. You give an example: 'a+(b+c*(e/f)+d)*g', which should trigger the following questions:
Is the language a single expression, or there may be multiple statements (separated by ';' maybe?
what are the 'a', 'b', ... 'g' tokens? Is it variable? What is the syntax of variables? Is it a C-like variable, or is it a single alphanumeric character as your example may imply.
There are 3 binary expression in your example. Is that all? Does the language also support '-'. Does your language support logical, and bit-wise operators?
Does the language support number literals? integer only? double? Does the language support string literals? Do you quote string literals?
Syntax for comments?
Which operator has precedence? Does '*' operator has precedence over '+' as in the example? Does operands evaluated right to left or left to right?
Any Pre-processing?
Once you are equipped with a good definition of the language syntax, start with implementing a tokenizer. A tokenizer gets a stream of characters and generates a list of tokens. In the example above, each character is a token, but in var*12 (var power 12) there are 3 tokens: 'var', '*' and '12'. If regular expression is permitted, it is possible you can do this part of the parsing with regular expressions.
Next, have a function that identify each token by type: is it an operator, is it a variable, a number literal, string literal, etc. Package all in a method called NextToken that returns a token and its type.
Finally, start parsing. In your sample above the root of the parsing tree will be a node with the '+' operator (which has precedence over the ''). The left child is a variable token 'a' and the right child is a tree with a root element the '' token. Work recursively.
Simple way out is to convert your expression into postfix notation (abcef/*++) & then refer to the answer to this question (http://stackoverflow.com/questions/423898/postfix-notation-to-expression-tree) for converting the postfix expression to a Tree.
This is what the interviewer expected :)
Whenever you intend to write a parser, the main question to ask is if you want to do it manually, or to use a parser generator framework.
In this case, I would say that it's a good exercise to write it all yourself.
Start with a good representation for the tree itself. This will be be output of your algorithm. For example, this could be a collection of objects, where one object kind could represent a "label" like a, b, and c in your example. Others could represent numbers. You could then defined a representation of operators, for example + is a binary operator, which would have two subobjects, representing the left and right subexpression.
Next step is the actual parser, I would suggest a classical recursive decent parser. One text describing this, and provides a standard pseudo-code implementation is this text by Theodore Norvell
I'd start with a simple grammar, something like those used by ANTLR and JavaCC.

Resources