How to specify mathematical expression using Z speification? - specifications

how can i specify a mathematical expression using Z notation ?
I think free types is appropriate for this situation because expressions has a recursive nature. please consider that we can have parenthesis and variables in our expression. and only ( + , - , / , * ) is allowed. for example :
A + 2 * ( 3 - B ) / 4
please help me ...

You need to use the axiomatic definition: the definition of an object is constrained by conditions.
There is a schema specified in zet for this.
Which is
| Declaration
------------------------------
| Predicate
|
|
A recursive example given:
[USERNAME] - An already defined type.
Given a username and a sequence of usernames(N1 --> USERNAME) return the number that the given username appears into the sequence.
|-occurs- USERNAME X seq USERNAME → N //here you define the input and what is returned.
---------------------------------------
|∀ u: USERNAME, s: seq USERNAME then
|s = < > => occurs(u,s) = 0
|s ≠ < > and head(s) = u => occurs(u,s) = 1+occurs(u,tail(s))
|s ≠ < > and head(s) ≠ u => occurs(u,s) = occurs(u,tail(s))

Related

How to generate arbitrary instances of a language given its concrete syntax in Rascal?

Given the concrete syntax of a language, I would like to define a function "instance" with signature str (type[&T]) that could be called with the reified type of the syntax and return a valid instance of the language.
For example, with this syntax:
lexical IntegerLiteral = [0-9]+;
start syntax Exp
= IntegerLiteral
| bracket "(" Exp ")"
> left Exp "*" Exp
> left Exp "+" Exp
;
A valid return of instance(#Exp) could be "1+(2*3)".
The reified type of a concrete syntax definition does contain information about the productions, but I am not sure if this approach is better than a dedicated data structure. Any pointers of how could I implement it?
The most natural thing is to use the Tree data-type from the ParseTree module in the standard library. It is the format that the parser produces, but you can also use it yourself. To get a string from the tree, simply print it in a string like so:
str s = "<myTree>";
A relatively complete random tree generator can be found here: https://github.com/cwi-swat/drambiguity/blob/master/src/GenerateTrees.rsc
The core of the implementation is this:
Tree randomChar(range(int min, int max)) = char(arbInt(max + 1 - min) + min);
Tree randomTree(type[Tree] gr)
= randomTree(gr.symbol, 0, toMap({ <s, p> | s <- gr.definitions, /Production p:prod(_,_,_) <- gr.definitions[s]}));
Tree randomTree(\char-class(list[CharRange] ranges), int rec, map[Symbol, set[Production]] _)
= randomChar(ranges[arbInt(size(ranges))]);
default Tree randomTree(Symbol sort, int rec, map[Symbol, set[Production]] gr) {
p = randomAlt(sort, gr[sort], rec);
return appl(p, [randomTree(delabel(s), rec + 1, gr) | s <- p.symbols]);
}
default Production randomAlt(Symbol sort, set[Production] alts, int rec) {
int w(Production p) = rec > 100 ? p.weight * p.weight : p.weight;
int total(set[Production] ps) = (1 | it + w(p) | Production p <- ps);
r = arbInt(total(alts));
count = 0;
for (Production p <- alts) {
count += w(p);
if (count >= r) {
return p;
}
}
throw "could not select a production for <sort> from <alts>";
}
Tree randomChar(range(int min, int max)) = char(arbInt(max + 1 - min) + min);
It is a simple recursive function which randomly selects productions from a reified grammar.
The trick towards termination lies in the weight of each rule. This is computed a priori, such that every rule has its own weight in the random selection. We take care to give the set of rules that lead to termination at least 50% chance of being selected (as opposed to the recursive rules) (code here: https://github.com/cwi-swat/drambiguity/blob/master/src/Termination.rsc)
Grammar terminationWeights(Grammar g) {
deps = dependencies(g.rules);
weights = ();
recProds = {p | /p:prod(s,[*_,t,*_],_) := g, <delabel(t), delabel(s)> in deps};
for (nt <- g.rules) {
prods = {p | /p:prod(_,_,_) := g.rules[nt]};
count = size(prods);
recCount = size(prods & recProds);
notRecCount = size(prods - recProds);
// at least 50% of the weight should go to non-recursive rules if they exist
notRecWeight = notRecCount != 0 ? (count * 10) / (2 * notRecCount) : 0;
recWeight = recCount != 0 ? (count * 10) / (2 * recCount) : 0;
weights += (p : p in recProds ? recWeight : notRecWeight | p <- prods);
}
return visit (g) {
case p:prod(_, _, _) => p[weight=weights[p]]
}
}
#memo
rel[Symbol,Symbol] dependencies(map[Symbol, Production] gr)
= {<delabel(from),delabel(to)> | /prod(Symbol from,[_*,Symbol to,_*],_) := gr}+;
Note that this randomTree algorithm will not terminate on grammars that are not "productive" (i.e. they have only a rule like syntax E = E;
Also it can generate trees that are filtered by disambiguation rules. So you can check this by running the parser on a generated string and check for parse errors. Also it can generated ambiguous strings.
By the way, this code was inspired by the PhD thesis of Naveneetha Vasudevan of King's College, London.

Can't demonstrate why !A&B OR !A&C OR !C&B = !C&B OR !A&C

I'm beginning a course on boolean logic and I got this boolean expression I need to prove. After a few hours of research I tried Wolfram Alpha, but unlike other equations it doesn't explain step-by-step how it simplified the longer expression. It's also pretty easy to see the (!A&B) isn't necessary in the expression with truth tables, but I can't demonstrate it. How should I do it?
The expression:
!A&B OR !A&C OR !C&B = !C&B OR !A&C
And a link to the Wolfram Alpha input: Wolfram
Thanks in advance, have a nice day.
Here is a derivation
!A&B | !A&C | !C&B
= !A&B&(C | !C) | !A&C&(B | !B) | !C&B&(A | !A) // x & T = x
= !A&B&C | !A&B&!C | !A&B&C | !A&!B&C | A&B&!C | !A&B&!C // distributive
= !A&B&C | !A&B&!C | !A&!B&C | A&B&!C // x | x = x
= !A&B&!C | A&B&!C | !A&B&C | !A&!B&C // commutative
= B&!C&(!A | A) | !A&C&(B | !B) // distributive
= B&!C | !A&C // x | !x = T, x & T = x
There are two ways of proving these kinds of equalities. One is formal: find a chain of equalities that arrive to the target formula. The other is intuitive: understand why the equality holds. Let me try the latter.
In your case, after rewriting the left hand side of your equation we have to show that:
(!C&B OR !A&C) OR !A&B = !C&B OR !A&C
which has the form p OR q = p, right?
So the question becomes: when p OR q = p? In other words, when q adds nothing to p? Well, if p is a consequence of q then q adds nothing to p. This is if q -> p (i.e., p is a consequence of q) then p OR q = p (please prove this formally!)
So, we have to show that !C&B OR !A&C is a consequence of !A&B. But this is easy because !A&B=true implies A=false and B=true. So, if C=false we have !C&B=true and if C=true then !A&C = true. Hence in both cases we have !C&B OR !A&C = true.

Simplifying Boolean Expressions with DeMorgan’s law

I need help simplifying the following Boolean expressions using DeMorgan’s law:
a) [ (AB)' + (CD)' ]'
and
b) [(X+Y)' + (X+Y') ]'
Please show some steps so I can do the other ones myself
a)
First step is the outermost negation: distribute it.
((AB)')'*((CD)')'
You see we have double negations which means the expression itself. (p')' = p
therefore
ABCD
[ (AB)' + (CD)' ]' --> ABCD
b)
Distribute the outermost negation:
((X+Y)')'(X+Y')'
get rid of the double negation:
(X+Y)(X+Y')'
again, distribute the negation (the one at the outer part of the expression):
(X+Y)(X'Y)
When you distribute (X+Y), we get
XX'Y + YX'Y
Since there is XX' in the first part of disjunction, the expression XX'Y equals to 0 (False).
Multiple instances of the same thing in an expression is the same thing itself. ppp = p.
Therefore:
0 + YX' --> YX'
[ (X+Y)' + (X+Y') ]' --> YX'
Im sorry for non-formal language:) hope it helps.
Steps are included:
a: [ (AB)' + (CD)' ]' = (AB)'' * (CD)'' = (AB) * (CD) = ABCD
b: [ (X+Y)' + (X+Y') ]' = (X+Y)'' * (X+Y')' = (X+Y) * (X'*Y) .. Simplifying this further relies on the distributive property.

How to convert a Maple expression x*y to Matlab for the result x.*y?

A Maple expression (for example, x^3+x*y) can be converted to Matlab by
with(CodeGeneration):
Matlab(x^3+x*y);
However, in Matlab, there are two kinds of product: A*B and A.*B. The above way will give x^3+x*y. Is there a convenient way to get the result x.^3+x.*y?
The language definition for Maple's CodeGeneration[Matlab] can be extended to handle various instances of the elementwise tilde (~) operator.
Since 'x*~y' seems to automatically simplify to `~`[`*`](x, ` $`, y), and since there appears to be a hard-coded error emitted by the presence of the name " $", then that name is substituted by NULL in the usage code below.
> restart:
> with(CodeGeneration): with(LanguageDefinition):
> LanguageDefinition:-Define("NewMatlab", extend="Matlab",
> AddFunction("`~`[`^`]", [Vector,integer]::Vector,
> proc(X,Y)
> Printer:-Print(X,".^",Y)
> end proc,
> numeric=double),
> AddFunction("`~`[`*`]", [Vector,integer]::Vector,
> proc(X,Y)
> Printer:-Print(X,".*",Y)
> end proc,
> numeric=double));
> expr:=''x^~y + x^~3 + x*~y'':
> Translate(subs(` $`=NULL, expr ), language="NewMatlab");
cg = x.^y + x.^3 + x.*y;
> p := proc(x,y)
> x^~y + x^~3 + x*~y;
> end proc:
> f := subs(` $`=NULL, eval(p) ):
> Translate(f, language="NewMatlab");
function freturn = f(x, y)
freturn = x.^y + x.^3 + x.*y;
For whatever it's worth, Maple 2015 can do this translation directly, without the extra help kindly provided by acer:
> f := (x,y)->x^~y + x^~3 + x*~y:
> CodeGeneration:-Matlab(f);
function freturn = f(x, y)
freturn = x .^ y + x .^ 3 + x .* y;
If the Matlab(x^3+x*y) expression gives out the code x^3+x*y in written format, then you can simply convert it into x.^3+x.y , just by using "Find & Replace" option of any notepad application. Just find all "" and "^" , and then replace them with ".*" and ".^" .
Hope this helps.

How to write the following boolean expression?

I've got three boolean values A, B and C. I need to write an IF statement which will execute if and only if no more than one of these values is True. In other words, here is the truth table:
A | B | C | Result
---+---+---+--------
0 | 0 | 0 | 1
0 | 0 | 1 | 1
0 | 1 | 0 | 1
0 | 1 | 1 | 0
1 | 0 | 0 | 1
1 | 0 | 1 | 0
1 | 1 | 0 | 0
1 | 1 | 1 | 0
What is the best way to write this? I know I can enumerate all possibilities, but that seems... too verbose. :P
Added: Just had one idea:
!(A && B) && !(B && C) && !(A && C)
This checks that no two values are set. The suggestion about sums is OK as well. Even more readable maybe...
(A?1:0) + (B?1:0) + (C?1:0) <= 1
P.S. This is for production code, so I'm going more for code readability than performance.
Added 2: Already accepted answer, but for the curious ones - it's C#. :) The question is pretty much language-agnostic though.
how about treating them as integer 1's and 0's, and checking that their sum equals 1?
EDIT:
now that we know that it's c#.net, i think the most readable solution would look somewhat like
public static class Extensions
{
public static int ToInt(this bool b)
{
return b ? 1 : 0;
}
}
the above tucked away in a class library (appcode?) where we don't have to see it, yet can easily access it (ctrl+click in r#, for instance) and then the implementation will simply be:
public bool noMoreThanOne(params bool[] bools)
{
return bools.ToList().Sum(b => b.ToInt()) <= 1;
}
...
bool check = noMoreThanOne(true, true, false, any, amount, of, bools);
You shold familiarize yourself with Karnaugh maps. Concept is most often applied to electronics but is very useful here too. It's very easy (thought Wikipedia explanation does look long -- it's thorough).
(A XOR B XOR C) OR NOT (A OR B OR C)
Edit: As pointed out by Vilx, this isn't right.
If A and B are both 1, and C is 0, A XOR B will be 0, the overall result will be 0.
How about:
NOT (A AND B) AND NOT (A AND C) AND NOT (B AND C)
If you turn the logic around, you want the condition to be false if you have any pair of booleans that are both true:
if (! ((a && b) || (a && c) || (b && c))) { ... }
For something completely different, you can put the booleans in an array and count how many true values there are:
if ((new bool[] { a, b, c }).Where(x => x).Count() <= 1) { ... }
I'd go for maximum maintainability and readability.
static bool ZeroOrOneAreTrue(params bool[] bools)
{
return NumThatAreTrue(bools) <= 1;
}
static int NumThatAreTrue(params bool[] bools)
{
return bools.Where(b => b).Count();
}
There are many answers here, but I have another one!
a ^ b ^ c ^ (a == b && b == c)
A general way of finding a minimal boolean expression for a given truth table is to use a Karnaugh map:
http://babbage.cs.qc.edu/courses/Minimize/
There are several online minimizers on the web. The one here (linked to from the article, it's in German, though) finds the following expression:
(!A && !B) || (!A && !C) || (!B && !C)
If you're going for code readability, though, I would probably go with the idea of "sum<=1". Take care that not all languages guarantee that false==0 and true==1 -- but you're probably aware of this since you've taken care of it in your own solution.
Good ol' logic:
+ = OR
. = AND
R = Abar.Bbar.Cbar + Abar.Bbar.C + Abar.B.Cbar + A.Bbar.Cbar
= Abar.Bbar.(Cbar + C) + Abar.B.Cbar + A.Bbar.Cbar
= Abar.Bbar + Abar.B.Cbar + A.Bbar.Cbar
= Abar.Bbar + CBar(A XOR B)
= NOT(A OR B) OR (NOT C AND (A XOR B))
Take the hint and simplify further if you want.
And yeah, get your self familiar with Karnaugh Maps
Depends whether you want something where it's easy to understand what you're trying to do, or something that's as logically simple as can be. Other people are posting logically simple answers, so here's one where it's more clear what's going on (and what the outcome will be for different inputs):
def only1st(a, b, c):
return a and not b and not c
if only1st(a, b, c) or only1st(b, a, c) or only1st(c, a, b):
print "Yes"
else:
print "No"
I like the addition solution, but here's a hack to do that with bit fields as well.
inline bool OnlyOneBitSet(int x)
{
// removes the leftmost bit, if zero, there was only one set.
return x & (x-1) == 0;
}
// macro for int conversion
#define BOOLASINT(x) ((x)?1:0)
// turn bools a, b, c into the bit field cba
int i = (BOOLASINT(a) << 0) | BOOLASINT(b) << 1 | BOOLASINT(c) << 2;
if (OnlyOneBitSet(i)) { /* tada */ }
Code demonstration of d's solution:
int total=0;
if (A) total++;
if (B) total++;
if (C) total++;
if (total<=1) // iff no more than one is true.
{
// execute
}