Specific conversion of EBNF into BNF - bnf

<A> ::= <B> x {<B> <D>} y <B>
<B> ::= <C> (w|z) <C> <D>
<C> := m [n] <D> <E>
<D> := q | null
<E> := p | null
How would you convert this EBNF into BNF?

Different people use a different syntax for EBNF, and I'm not sure which one you are using. Your grammar in EBNF (ISO/IEC 14977: 1996(E)) would look like this:
A = B, "x", {B, D}, "y", B;
B = C, ("w" | "z"), C, D;
C = "m", ["n"], D, E;
D = ["q"];
E = ["p"];
Assuming you use null for the empty string. Notice that this could be further simplified.
Some productions must be added to convert this to BNF:
{ expr } can be replaced by inserting a production P := empty |
expr P where empty represents the empty string.
[ expr ] can be replaced by inserting P := empty | expr.
Any expression ( expr ) can be replaced by adding a new production
P := expr.
So something like this:
A -> B x F y B
F -> empty | B D F
B -> C G C D
G -> w | z
C -> m H D E
H -> empty | n
D -> q | empty
E -> p | empty
Again, assuming that with null you mean the empty string.

Related

Simplifying 5-var Boolean SOP Expression using the Laws and Properties

I have this question that is messing me up because I am not getting that where should I start, which terms should I pick at the beginning? Because this confusing expression does not even let me take the common as it makes no sense. Also, it does not even let me remove compliments (using the Laws) as it also does not make any sense. Please help me in this, at least just guide me what should I do? From where should I start? I would be really grateful.
The Explanation of Symbols I used to write the expression:
! : NOT Gate
+ : OR Gate
. (dot) : AND Gate
Boolean Expression:
A.!B.E + !(B.C).D.!E + !(C.D).E+!A.D.!E + A.!(C.D).E + A.E + A.B.!E + !(A.C) + B.C.!D
I have used an online expression simplifier and that gave me the following answer:
!A + B + !C + D + E
But how the above long expression has been simplified in this short one? I know the Laws and Properties but I am not getting that how should I start simplifying the long one? Which terms should I see first? Kindly anyone please help me.
(This is a direct answer to your comment, and a side-ways answer to your main question. In short, use a different method to get the desired simplified expression.)
You have a complicated expression, but one that uses only 5 logical variables. In this problem it would be much easier to build a truth table, which would have just 2^5 = 32 rows. You could look at the results and use those to build a simplified, equivalent expression. This does not use "the laws and properties" that your original question requires, but it is a standard technique to simplify Boolean expressions.
You should have learned how to build a truth table in just about any Discrete Mathematics class. In short, you make a table where each element in each row is a T for True or F for False. The rows contain all possible combinations of Ts and Fs. For 5 variables this would use 2^5 = 32 rows. For each row, you assign the first value to A, the second to B, etc. You then evaluate the expression for those values and write the result at the end of the line.
This can be done by hand, but your expression is complicated enough that we could avoid that. Here is a Python 3 script that prints the desired table. Note that Python has the product() function which simplifies getting all possible combinations of Ts and Fs. This script used B[] to convert a Boolean value to a single character T or F.
from itertools import product
"""Make a truth table for the Boolean expression
A.!B.E + !(B.C).D.!E + !(C.D).E+!A.D.!E + A.!(C.D).E + A.E + A.B.!E + !(A.C) + B.C.!D
"""
B = ('F', 'T')
print('A B C D E : Result')
print('- - - - - : ------')
for a, b, c, d, e in product((True, False), repeat=5):
print(B[a], B[b], B[c], B[d], B[e], end=' : ')
print(B[
(a and not b and e)
or (not (b and c) and d and not e)
or (not (c and d) and e)
or (not a and d and not e)
or (a and not (c and d) and e)
or (a and e)
or (a and b and not e)
or (not (a and c))
or (b and c and not d)
])
Here are the results:
A B C D E : Result
- - - - - : ------
T T T T T : T
T T T T F : T
T T T F T : T
T T T F F : T
T T F T T : T
T T F T F : T
T T F F T : T
T T F F F : T
T F T T T : T
T F T T F : T
T F T F T : T
T F T F F : F
T F F T T : T
T F F T F : T
T F F F T : T
T F F F F : T
F T T T T : T
F T T T F : T
F T T F T : T
F T T F F : T
F T F T T : T
F T F T F : T
F T F F T : T
F T F F F : T
F F T T T : T
F F T T F : T
F F T F T : T
F F T F F : T
F F F T T : T
F F F T F : T
F F F F T : T
F F F F F : T
We see that the result is always T except for the single line T F T F F. This means your expression is true unless A is True, B is False, C is True, and D and E are False. So we can simplify your expression (using your notation) to
!(A.!B.C.!D.!E)
A simple use of DeMorgan's laws changes this to normal form:
!A + B + !C + D + E
which is what you wanted.

Name of a common pattern-matching functional operator

In functional programming, what is the name (or name of the concept) of the following functional operator P?:
Given two functions f and g, and predicate function p, P(p, f, g) is the function
x → if (p(x)) f(x) else g(x)
I am wondering whether this operator has an established name, so that I can use that name in my code. (That is, I want to give P a conventional name.)
I would say it's the if operator lifted into the function monad.
For example in Haskell, you can literally do
import Control.Monad
let if' c t f = if c then t else f -- another common name is `ite`
let ifM = liftM3 if' -- admittedly the type of this is too generic
-- ^^^^^^^^^^
let example = ifM even (\x -> "t "++show x) (\x -> "f "++show x)
example 1 -- "f 1"
example 2 -- "t 2"
Another haskell example Point-wise conditional in Boolean library
cond :: (Applicative f, IfB a, bool ~ BooleanOf a) => f bool -> f a -> f a -> f a
it takes Applicative that holds bool, two another Applicatives with values for True and False cases and produces Applicative result.
There are different types that are Applicative and function is just one of them.
> f = cond (\x -> x > 1) (\x -> x / 10) (\x -> x * 10)
> f 2.0
# 0.2
> f 0.13
#1.3
Optional value Maybe is another useful example
> cond (Just True) (Just 10) (Just 20)
# Just 10
> cond (Just True) (Just 10) Nothing
# Nothing
List is also Applicative
> cond [True, False, True] [10] [1, 2]
# [10,10,1,2,10,10]
> cond [True, False, True] [10] [1]
# [10, 1, 10]
> cond [True, False, True] [10] []
# []

Is there a better way to write a right-recursive grammar's production rules than this?

Scenario: Give production rules for a RIGHT-recursive grammar that
describes the set of all non-empty strings made from the characters
R and N, which may contain arbitrarily many contiguous
repetitions of R, but precisely two or precisely three contiguous
repetitions of N.
Answer:
A -> N B | R+ A
B -> N D | N C | N ε
C -> N D | N ε
D -> R+ D | R ε
Incorrect:
A -> NNB | NNNB | RA | R
B -> R | RA | ε
edit: the above is not correct, I misunderstood the scenario.
Correct:
S -> RS | A
A -> NA | NB
B -> RB | RC
C -> NC | ND
D -> RD | RE | ε
E -> NE | NF
F -> RF | ε
How it works:
It starts with S, that can generate 0 or more R or move to A, which generates the first group of Ns. Then it moves to B, which generates the Rs between 1st and 2nd group of Ns. Then it move to C, which generates the 2nd group of Ns. Then it moves to D, which can generate 0 or more Rs and either finish or move to E, which generates the 3rd group of Ns. Lastly it moves to F, which generates 0 or more Rs.
This works just as well and is simpler:
S -> RS | A
A -> NA | NB
B -> RB | RC
C -> NC | ND
D -> RD | E
E -> NE | F
F -> RF | ε
It is the same up to D where instead of providing an ε option it provides an option to add another group of R's or go to E which is another group of N's, but this would not occur if there were no R's previously anyway as they would have been outputted as a conversion from C, and then another option to recursively add R's or an empty string.
Example parse tree generated from the input NRNR
S
\
A
/ \
N B
/ \
R C
/ \
N D
/ \
R D
\
E
\
F
\
ε

Manipulate unmutable variables inside of loop in OCaml

I have the following code in OCaml.I have defined all necesar functions and tested them step by step the evalution should work good but I didn't succed to manipulate the variables inside of while.How can I make x,vn,v to change their value?I think I should rewrite the while like a rec loop but can't figure out exactly:
Here is the rest of code: http://pastebin.com/Ash3xw6y
Pseudocode:
input : f formula
output: yes if f valid
else not
begin:
V =set of prop variables
eliminate from f => and <=>
while (V is not empty)
choose x from V
V =V -{x}
replace f with f[x->true]&&f[x->false]
simplify as much as possible f
if f is evaluated with true then return true
else if (not f) is evaluated true then return false
end if
end while
return false
end
type bexp = V of
| string
| B of bool
| Neg of bexp
| And of bexp * bexp
| Or of bexp * bexp
| Impl of bexp * bexp
| Eqv of bexp * bexp
module StringSet=Set.make(String)
let is_valide f=
let v= stringset_of_list (ens f []) in (*set of all variables of f *)
let g= elim f in (*eliminate => and <=> *)
let quit_loop=ref false in
while not !quit_loop
do
let x=StringSet.choose v in
let vn=StringSet.remove x v in
if StringSet.is_empty vn=true then quit_loop:=true;
let h= And( replace x (B true) g ,replace x (B false) g)in
let j=simplify h in
if (only_bools j) then
if (eval j) then print_string "yes"
else print_string "not"
done
(New form)
let tautology f =
let rec tautology1 x v g =
let h= And( remplace x (B true) g ,remplace x (B false) g)in
let j= simplify h in
if not (only_bools j) then tautology (StringSet.choose (StringSet.remove x v) (StringSet.remove x v) j
else
if (eval1 j) then print_string "yes \n " else
if (eval1 (Neg (j))) then print_string "not \n";
in tautology1 (StringSet.choose (stringset_of_list (ens f [])) (stringset_of_list (ens f [])) (elim f);;
while loop belongs to imperative programming part in OCaml.
Basically, you can't modify immutable variables in while or for loops or anywhere.
To let a variable to be mutable, you need to define it like let var = ref .... ref is the keyword for mutables.
Read these two chapters:
https://realworldocaml.org/v1/en/html/a-guided-tour.html#imperative-programming
https://realworldocaml.org/v1/en/html/imperative-programming-1.html
You can define x,vn,v as refs, but I guess it will be ugly.
I suggest you think your code in a functional way.
Since you haven't placed functions ens etc here, I can't produce an example refine for u.

Pattern-matching returning a string representation of math expression

I have to write a function dump which takes an expression
type expression =
| Int of int
| Float of float
| Add of expression * expression
| Sub of expression * expression
| Mult of expression * expression
| Div of expression * expression
;;
and returns a string representation of it.
For example:
dump (Add (Int 1, Int 2));;
dump (Mult (Int 5, Add(Int 2, Int 3)), Int 1)
should return respectively
- : string = "1+2"
- : string = "5*(2+3)-1"
I've written something like this:
let rec dump e = match e with
| Int a -> string_of_int a
| Float a -> string_of_float a
| Add (e1,e2) -> "(" ^ (dump e1) ^ "+" ^ (dump e2) ^ ")"
| Sub (e1,e2) -> "(" ^ (dump e1) ^ "-" ^ (dump e2) ^ ")"
| Mult (e1,e2) -> (dump e1) ^ "*" ^ (dump e2)
| Div (e1,e2) -> (dump e1) ^ "/" ^ (dump e2)
;;
and returned expressions are correct, but still not optimal.
(for Add (Int 1, Int 2)) it is (1+2) and should be 1+2 ). How can I fix this?
(without nested pattern matching which isn't a good idea)
Let's think about when you need parens:
First of all always wrapping parens around certain operations is the wrong approach. Whether a term needs to be parenthesized or not does not only depend on which operator is used in the term, but also which operator the term is an operand to.
E.g. when 1+2 and 3+4 are operands to +, it should be 1+2+3+4 - no parens. However if the operator is *, it needs to be (1+2) * (3+4).
So for which combinations of operators do we need parens?
The operands to + never need to be parenthesized. If the operands are products or quotients, they have higher precedence anyway, and if the operands are differences, you need no parens because x + (y - z) = x + y -z.
With - it's a bit different. * and / still don't need to be parenthesized because they have higher precedence, but + and - do iff they're in the second operand because x + y - z = (x + y) - z, but x - y + z != x - (y + z).
With Mult both operands need to be parenthesized if they're Add or Sub, but not if they're Mult or Div.
With Div the first operand needs to be parenthesized if it's Add or Sub and the second always needs to be parenthesized (unless it's an Int or Float, of course).
First, define a list of priority levels for your operators:
module Prio = struct
let div = 4
let mul = 3
let sub = 2
let add = 1
end
An useful construct is "wrap in brackets if this condition is true" :
let wrap_if c str = if c then "("^str^")" else str
Finally, define an auxiliary printing function which is provided with a "priority" argument meaning "by the way, you're wrapped in an expression which has priority X, so protect your output accordingly":
let dump e =
let rec aux prio = function
| Int a -> string_of_int a
| Float a -> string_of_float a
| Add (e1,e2) ->
wrap_if (prio > Prio.add) (aux Prio.add e1 ^ "+" ^ aux Prio.add e2)
| Sub (e1,e2) ->
wrap_if (prio > Prio.add) (aux Prio.add e1 ^ "-" ^ aux Prio.sub e2)
| Mult (e1,e2) ->
wrap_if (prio > Prio.mul) (aux Prio.mul e1 ^ "*" ^ aux Prio.mul e2)
| Div (e1,e2) ->
wrap_if (prio > Prio.mul) (aux Prio.mul e1 ^ "/" ^ aux Prio.div e2)
in aux Prio.add e
;;
It sounds to me like you want to build some set of reduction rules which can be applied to yield the "prettified" or most-reduced form of your expressions, based on order of operations and e.g. commutativity, associativity, etc. For instance (a + a) => a + a, (a * b) + c => a * b + c and so on.
A rather simple and yet rather generic answer (works for other syntaxes than mathematical expressions) : pick precedences (and, if you're picky, associativities) for your constructors, and only add parentheses when a subterm constructor has lower precedence than the current constructor.
More precisely : when you want to print a constructor C(x1,x2,x3..), you look at the head constructor of each xi (if x1 is D(y1,y2..), its head constructor is D), compare the precedence levels of C and D. If the precendence of D is lower, you add parenthesis around the string representation of x2.

Resources