Building a recursive string function - boolean

I am trying to build a function whose output is a list of all possible boolean expressions with an upper bound. For three variables p,q and r my function would be, theoretically:
f(0) = {p,q,r} // this notation refer to the mathematical set such that p,q and r belong to f(0).
f(n+1) = { (A & B) such that A and B belongs to f(n) } Union { (A or B) such that A and B belongs to f(n) } Union { (not A) such that A belongs to f(n) }
I want to receive a matrix whose rows are the strings of all the possible strings corresponding to boolean formulas build by n iterations of the function. For example:
f(2)=['p' ; 'q' ; 'r' ; '(p&q)' ; 'p&(p or q)' ; 'r or (p & r)' ; ... ]

Related

How to declare a class for a calculator?

I am trying to build my own calculator in Haskell with class declaration.
Firstly, I was trying to implement the addition, but here I got the error:
Couldn't match expected type 'Exp -> Double' with actual type 'Exp'
data Exp = Number Double | Add Exp Exp
class Calc a where
calculate :: a -> a -> Double
instance Calc Exp where
calculate (Add a b) = a + b
What do I have to change?
You don't really need, nor would I recommend, a class here. Just define an ordinary function that handles each of the data constructors separately. (Use a class only if you expect to have multiple types that can be used with calculate.)
In either case, calculate takes a single argument, as your type represents an entire expression, operands and operator together.
calculate :: Exp -> Double
calculate (Number n) = ...
calculate (Add a b) = ...
Keep in mind that a and b are values of type Exp, not numbers (i.e., types with a Num instance) that you can add directly. (This suggests you need to recursively calculate the value of a and b before you can actually perform addition.)
Some test cases for you to consider:
n1 = Number 2.0
n2 = Add (Number 3.0) (4.0))
n3 = Add n1 n2
map calculate [n1, n2, n3] == [2.0, 7.0, 9.0]
As suggested by chepner, your calculate function need only take a single argument. You also need to account for the possibility that each Exp value maybe be a Number and handle that in the function.
Since a and b are Exp values and not Num instances, you will need to apple calculate to them.
data Exp = Number Double | Add Exp Exp
class Calc a where
calculate :: a -> Double
instance Calc Exp where
calculate (Number n) = n
calculate (Add a b) = a' + b'
where a' = ...
where b' = ...
But you might consider making Exp an instance of Num. The below is incomplete as it doesn't account for actual expressions except for +, but it might hint at what's possible.
instance Num Exp where
(+) (Number n1) (Number n2) = Number (n1 + n2)
(+) (Add a b) c#(Number _) = a + b + c
(+) a#(Number _) (Add b c) = a + b + c
(+) (Add a b) (Add c d) = a + b + c + d
(*) (Number n1) (Number n2) = Number (n1 * n2)
abs (Number n) = Number (abs n)
negate (Number n) = Number (negate n)
signum (Number n) = Number (signum n)
fromInteger n = Number (fromIntegral n)
ghci> case Add (Number 5) (Number 6) + Number 7 of { Number n -> n }
18.0

How to express "implies" in ScalaCheck, say, "if an integer n * n = 0 then n = 0"?

I would like to use Scala's property-based testing tool ScalaCheck to express a property
if an integer n * n = 0 then n = 0
How can I write this property in ScalaCheck? I know for example
val myprop = forAll {(n: Int) => n + 1 - 1 = n}
But I do not know how to express "A implies B" in ScalaCheck (without reducing it to Not-A or B, which can look clumsy).
Use ==> (implication operator)
val prop = forAll { n: Int =>
(n * n == 0) ==> n == 0
}
(see their User Guide )
the catch is: in this particular example the condition is very hard to satisfy so ScalaCheck will give up after several tries (but at least it does tell you so, otherwise you get a false positive because your necessary condition was never checked). In that case you can provide a custom generator so that it will generate values that satisfy your condition.

How to know which Maple command automatically maps on list entries or not?

In Mathematica, almost all commands automatically thread (or map) over a list.
In Maple, how does one determine which command automatically acts over entries of a list or a set?
For example:
y+p*x=2*sqrt(x*y);
r:=[solve(%,y)];
This gives list of two entries (the solutions)
#r := [-p*x+(2*(1+sqrt(1-p)))*x, -p*x+(2*(1-sqrt(1-p)))*x]
Now I found that collect automatically maps on each list entry
collect(r,x);
# [(-p+2+2*sqrt(1-p))*x, (-p+2-2*sqrt(1-p))*x]
But another command does not (I just picked this one)
MmaTranslator[Mma][LeafCount](r);
#37
For the above one needs to explicitly iterate over the entries of a list or a set.
map(MmaTranslator[Mma][LeafCount],r)
#[17, 19]
Is there a way in Maple to find which command automatically threads over entries of a list or a set other than trial and error?
Maple 2018.1
I don't know of any place in the documentation that says exactly which commands will automatically map over a list.
But the collection of such commands is not large. The vast majority of commands will not automatically map over a list. Most of the ones which auto-map over a list relate to simplication or related manipulation of expressions. The collection of commands which auto-map over a list contains at least these:
collect, combine, expand,
evala, evalc, evalf,
factor, normal, radnormal, rationalize, simplify
The auto-mapping over lists for those commands is mostly a convenience to provide a shorter syntax than wrapping explicitly with the map command.
There are also commands which preserve structure (unless explicitly
told, via options, that the outer list structure is the thing to alter) and thus usually accomplish the same thing for a list as mapping over the list:
convert, eval, evalindets, subs, subsindets
Modern Maple has another shorter syntax which can map a command over a list (or a set, or a Vector, etc). It is called the "elementwise" operation, and its syntax consists of appending ~ (tilde) to the command.
Eg,
discont~( [ csc(x), sec(x) ], x );
[{Pi _Z1~}, {Pi _Z2~ + 1/2 Pi}]
As far as your other example goes, note that LeafCount computes a value (metric) for the first argument considered as a single expression. But a list of items is still a single expression. So it certainly should not be surprising that (without the ~) it acts on the list as a whole, rather than automatically mapping over it. It counts the enclosing list as an additional "leaf".
MmaTranslator:-Mma:-LeafCount( L0 );
8
L0 := [ sin(x), 1/2*x*cos(x) ]:
MmaTranslator:-Mma:-LeafCount~( L0 );
[2, 5]
map( MmaTranslator:-Mma:-LeafCount, L0 );
[2, 5]
For an example similar to your original there is no difference in applying collect (which auto-maps) and applying it elementwise with collect~. Here, the first two results are the same because the addtional argument, x, happens to be a scalar. Eg,
r := [p*x+(2*(x^2+p^2))*x, p*x+(2*(x^2-p^2))*x]:
collect(r, x);
3 2 3 2
[2 x + (2 p + p) x, 2 x + (-2 p + p) x]
collect~(r, x);
3 2 3 2
[2 x + (2 p + p) x, 2 x + (-2 p + p) x]
map(collect, r, x);
3 2 3 2
[2 x + (2 p + p) x, 2 x + (-2 p + p) x]
I should mention that the above examples will behave differently if the second argument is a list such as [x,p] rather than a scalar such as x.
s := [a*b+(2*(a^2*b+b^2))*a, a*b+(2*(a^2*b-b^2))*a]:
collect(s, [a,b]);
3 2 3 2
[2 b a + (2 b + b) a, 2 b a + (-2 b + b) a]
map(collect, s, [a,b]);
3 2 3 2
[2 b a + (2 b + b) a, 2 b a + (-2 b + b) a]
collect~(s, [a,b]);
3 2 2 3
[2 b a + (2 b + b) a, -2 a b + (2 a + a) b]
zip(collect, s, [a,b]);
3 2 2 3
[2 b a + (2 b + b) a, -2 a b + (2 a + a) b]
In the above, the elementiwise collect~ example acts like zip when the second argument is also a list. That is, the first item in the first argument is collected wrt the first item in the second argument, and the second item in the first argument is collected wrt to the second item in the second argument.
Another feature of the elementwise operator syntax is that it will not map the command over the operands of a scalar expression (ie. not a list, set, Vector, etc). This is in stark contrast to map, which can be used to map an operation over the operands of an expression.
Here are two examples where map applies the command to the operands of a scalar expression, while using elementwise ~ gets the command applied only to the scalar expression itself. In the first example the operands are the summands of a sum of terms. In the second example the operands are the arguments of an unevaluated function call.
T := x^2 * sin(x) + y^2 * cos(x):
F( T );
2 2
F(x sin(x) + y cos(x))
F~( T );
2 2
F(x sin(x) + y cos(x))
map( F, T );
2 2
F(x sin(x)) + F(y cos(x))
G( arctan(a, b) );
G(arctan(a, b))
G~( arctan(a, b) );
G(arctan(a, b))
map( G, arctan(a, b) );
arctan(G(a), G(b))
So, if you don't want to map a command inadvertantly over the operands of a scalar expression (addend, multiplicands, etc) then you can use the elementwise ~ syntax without having to first test whether the first expression is a scalar or a list (etc).
Again, if there is an additional argument then it makes a difference whether it is a scalar to a list.
F( T, a );
F(sin(x) + cos(x), a)
F~( T, a );
F(sin(x) + cos(x), a)
map( F, T, a );
F(sin(x), a) + F(cos(x), a)
F( T, [a,b] );
F(sin(x) + cos(x), [a, b])
map( F, T, [a,b] );
F(sin(x), [a, b]) + F(cos(x), [a, b])
F~( T, [a,b] );
[F(sin(x) + cos(x), a), F(sin(x) + cos(x), b)]
zip( F, T, [a,b] );
[F(sin(x) + cos(x), a), F(sin(x) + cos(x), b)]

Boolean Expression Optimization For All AND Conditions

I am trying to solve the boolean expression optimization problem for a simple rule engine.
Here is what I am trying to do, lets say if I have following 5 conditions (where a,b,c,d,e,f are complex boolean expressions)
if (a AND b AND c AND d AND e AND f) then do-1
if (a AND b AND c AND d AND e) then do-2
if (a AND b AND c AND d) then do-3
if (a AND b AND c) then do-4
if (a AND b) then do-5
In case when I execute these conditions in a linear order I will
- evaluate "a" for 5 times
- evaluate "b" for 5 times
- evaluate "c" for 4 times
- evaluate "d" for 3 times
- evaluate "e" for 2 times
- evaluate "f" for 1 time
I would like to make a expression execution tree from this so that each expression (a,b,c,d,e,f) is evaluated minimum number of times.
The perfect solution will be that each expression is evaluated only once. I think this can be achieved with a tree creation where all these conditions are part of a tree.
The tree may look like this
if(a AND b) then do-5 {
if(c) then do-4 {
if(d) then do-3 {
if(e) then do-2 {
if(f) then do-1
}
}
}
}
My questions is - How can I make this tree from the set of boolean expressions listed above?
Related Questions:
Algorithm for evaluating nested logical expression
Converting an expression to conjunctive normal form with a twist
Is it useful in C# to apply DeMorgan's theorem to manually optimize boolean expressions in conditional statements (e.g. if conditions)
You could approach it this way:
var booleans = [a, b, c, d, e, f];
var i = 0;
while(booleans[i]) i++;
switch(i) {
case 0:
// do something
break;
case 1:
// do something
break;
...
}
I'm pretty sure there is a way to merge the while loop with the switch operator to get something even more optimized from this.

list comprehension without parentheses in a function

I have a function that needs to return the last property of an object that satisfies the condition:
types = {
a: 1,
b: 2,
c: 3
}
g = (s) -> v for k, v of types when k is s
console.log g 'b'
this code prints [ 2 ]
I expected just 2, and not an array. And indeed, this code does print what I expect:
console.log v for k, v of types when k is 'b'
What is wrong?
P.S. I know that instead of this function I can just access the object's property using [], but this is a contrived example.
If we rearrange the code then things should be clearer.
Your second piece of code:
console.log v for k, v of types when k is 'b'
is just another way of writing this:
for k, v of types when k is 'b'
console.log(v)
or even:
for k, v of types
if k is 'b'
console.log(v)
Since there is only one 'b' key, only one console.log call is made.
Your first piece of code:
g = (s) -> v for k, v of types when k is s
is the same as this:
g = (s) ->
a = (v for k, v of types when k is s)
a
The loop, v for k, v of types when k is s yields an array by definition so a will be an array (with only one element) and g will return an array.
console.log v for k, v of types when k is 'b' will call console.log(v) for every v when k satisfies the condition whereas your first code snipped will call console.log(g(b)). If there were two elements in types that satisfied the condition, the outputs would be:
[1, 2]
and
1
2
To make g output the first element that satisfies the condition, you could use return with early out or just take the first element of the results array.
g = (s) -> return v for k, v of types when k is s