Defining boolean logic operators(v, ^, XOR, ->, <->) - c++11

Say we have bool true = (P v Q) -> R
How would I define an operator(or a function), so that the symbols(v, ^, XOR, ->, <->), would call the function that would perform the logic?
So, in example: bool true = P v Q, would call bool or(bool a, bool b)

It is not possible to define arbitrary infix operators in C++, and you also can’t use the name true as a variable name.
However, C++ already provides || for or, && for and, ^ or != for xor (for bools, they’re equivalent), and ! for not. If you want logical implication you’d best use !P || Q, and if you want iff, you should use P == Q.

Related

How to verify solutions for Logic functions having ampersand symbol (used in Logic package)

For example, if we have a logic function F = (x1 or x2) and (not x2) then we can verify a solution [x1=true, x2=false] of equation F = true this way:
[> F:=(x1 or x2) and (not x2):
subs({x1=true,x2=false},F);
true
Maple Logic package has a nice function Satisfy, which can find a solution, but function F (now it's named as G) has to be written using symbol & (before and, or, not):
[> G:=(x1 &or x2) &and (&not x2):
A:=Logic[Satisfy](G);
A := {x1 = true, x2 = false}
But I don't know an easy way how to verify a solution (I mean not in this specific case, but in general, functions may have hundreds of variables). My attempt was to use substitution and then use evalb, but it didn't work:
[> G1:=subs(A,G);
evalb(G1);
G1:= (true &or false) &and &not(false)
(true &or false) &and &not(false)
But for function F the substitution worked (even without evalb):
[> F1:=subs(A,F);
F1:=true
Also I couldn't find an easy way to remove ampersand symbol & from an expression (in order to construct function F from function G).
G := (x1 &or x2) &and (&not x2):
cand := {x1=true, x2=false}:
Given the logical expression assigned to G in form of used by the Logic package (ie. operators with names prefixed by &), then the candidate solution assigned to cand can be tested as follows:
BG := Logic:-Export(G, form=boolean);
BG := (x1 or x2) and not x2
eval(BG, cand);
true
Combining those two steps,
eval(Logic:-Export(G, form=boolean), cand);
true
Another solution similar to #acer's, but the opposite direction. If you are not using anything else other than Satisfy from the Logic package and you are fine with having your logical formulas as in F in your example, then there is no need to have your formula saved in the Logic's style with ampersand operations. Instead of Export in #acer's answer, use Import. Here is how it works in your example.
F := (x1 or x2) and (not x2):
A := Logic:-Satisfy( Logic:-Import( F ) );
F1 := subs( A, F );
Note that Package:-Command is the same as Packae[Command] with tiny differences. You can also use eval( F, A ) instead of subs( A, F ). For their differences you can check Maple help pages. But here they give the same results as you want.

Algorithm for enumerating all permutations of algebraic expressions

If I have a list of variables, such as {A, B, C} and a list of operators, such as {AND, OR}, how can I efficiently enumerate all permutations of valid expressions?
Given the above, I would want to see as output (assuming evaluation from left-to-right with no operator precedence):
A AND B AND C
A OR B OR C
A AND B OR C
A AND C OR B
B AND C OR A
A OR B AND C
A OR C AND B
B OR C AND A
I believe that is an exhaustive enumeration of all combinations of inputs. I don't want to be redundant, so for example, I wouldn't add "C OR B AND A" because that is the same as "B OR C AND A".
Any ideas of how I can come up with an algorithm to do this? I really have no idea where to even start.
Recursion is a simple option to go:
void AllPossibilities(variables, operators, index, currentExpression){
if(index == variables.size) {
print(currentExpression);
return;
}
foreach(v in variables){
foreach(op in operators){
AllPossibilities(variables, operators, index + 1, v + op);
}
}
}
This is not an easy problem. First, you need a notion of grouping, because
(A AND B) OR C != A AND (B OR C)
Second, you need to generate all expressions. This will mean iterating through every permutation of terms, and grouping of terms in the permutation.
Third, you have to actually parse every expression, bringing the parsed expressions into a canonical form (say, CNF. https://en.wikipedia.org/wiki/Binary_expression_tree#Construction_of_an_expression_tree)
Finally, you have to actually check equivalence of the expressions seen so far. This is checking equivalence of the AST formed by parsing.
It will look loosely like this.
INPUT: terms
0. unique_expressions = empty_set
1. for p_t in permutations of terms:
2. for p_o in permutations of operations:
3. e = merge_into_expression(p_t, p_o)
4. parsed_e = parse(e)
5. already_seen = False
6. for unique_e in unique_expressions:
7. if equivalent(parsed_e, unique_e)
8. already_seen = True
9. break
10. if not already_seen:
11. unique_expressions.add(parsed_e)
For more info, check out this post. How to check if two boolean expressions are equivalent

Functional programming with OCAML

I'm new to functional programming and I'm trying to implement a basic algorithm using OCAML for course that I'm following currently.
I'm trying to implement the following algorithm :
Entries :
- E : a non-empty set of integers
- s : an integer
- d : a positive float different of 0
Output :
- T : a set of integers included into E
m <- min(E)
T <- {m}
FOR EACH e ∈ sort_ascending(E \ {m}) DO
IF e > (1+d)m AND e <= s THEN
T <- T U {e}
m <- e
RETURN T
let f = fun (l: int list) (s: int) (d: float) ->
List.fold_left (fun acc x -> if ... then (list_union acc [x]) else acc)
[(list_min l)] (list_sort_ascending l) ;;
So far, this is what I have, but I don't know how to handle the modification of the "m" variable mentioned in the algorithm... So I need help to understand what is the best way to implement the algorithm, maybe I'm not gone in the right direction.
Thanks by advance to anyone who will take time to help me !
The basic trick of functional programming is that although you can't modify the values of any variables, you can call a function with different arguments. In the initial stages of switching away from imperative ways of thinking, you can imagine making every variable you want to modify into the parameters of your function. To modify the variables, you call the function recursively with the desired new values.
This technique will work for "modifying" the variable m. Think of m as a function parameter instead.
You are already using this technique with acc. Each call inside the fold gets the old value of acc and returns the new value, which is then passed to the function again. You might imagine having both acc and m as parameters of this inner function.
Assuming list_min is defined you should think the problem methodically. Let's say you represent a set with a list. Your function takes this set and some arguments and returns a subset of the original set, given the elements meet certain conditions.
Now, when I read this for the first time, List.filter automatically came to my mind.
List.filter : ('a -> bool) -> 'a list -> 'a list
But you wanted to modify the m so this wouldn't be useful. It's important to know when you can use library functions and when you really need to create your own functions from scratch. You could clearly use filter while handling m as a reference but it wouldn't be the functional way.
First let's focus on your predicate:
fun s d m e -> (float e) > (1. +. d)*.(float m) && (e <= s)
Note that +. and *. are the plus and product functions for floats, and float is a function that casts an int to float.
Let's say the function predicate is that predicate I just mentioned.
Now, this is also a matter of opinion. In my experience I wouldn't use fold_left just because it's just complicated and not necessary.
So let's begin with my idea of the code:
let m = list_min l;;
So this is the initial m
Then I will define an auxiliary function that reads the m as an argument, with l as your original set, and s, d and m the variables you used in your original imperative code.
let rec f' l s d m =
match l with
| [] -> []
| x :: xs -> if (predicate s d m x) then begin
x :: (f' xs s d x)
end
else
f' xs s d m in
f' l s d m
Then for each element of your set, you check if it satisfies the predicate, and if it does, you call the function again but you replace the value of m with x.
Finally you could just call f' from a function f:
let f (l: int list) (s: int) (d: float) =
let m = list_min l in
f' l s d m
Be careful when creating a function like your list_min, what would happen if the list was empty? Normally you would use the Option type to handle those cases but you assumed you're dealing with a non-empty set so that's great.
When doing functional programming it's important to think functional. Pattern matching is super recommended, while pointers/references should be minimal. I hope this is useful. Contact me if you any other doubt or recommendation.

Matching head different from some pattern

I want to match expression who's head differs from f.
This works
[In] !MatchQ[t[3], x_ /; Head[x] == f]
[Out] True
But not this
[In] MatchQ[t[3], x_ /; Head[x] != f]
[Out] False
Why does the second solution not work? How can I make it work?
Why this does not work: you must use =!= (UnsameQ), rather than != (Unequal) for structural comparisons:
In[18]:= MatchQ[t[3],x_/;Head[x]=!=f]
Out[18]= True
The reason can be seen by evaluating this:
In[22]:= Head[t[3]]!=f
Out[22]= t!=f
The operators == (Equal) and != (Unequal) do evaluate to themselves, when the fact of equality (or inequality) of the two sides can not be established. This makes sense in a symbolic environment. I considered this topic in more detail here, where also SameQ and UnsameQ are discussed.
There are also more elegant ways to express the same pattern, which will be more efficient as well, such as this:
MatchQ[t[3],Except[_f]]

Passing parameters stored in a list to expression

How can I pass values to a given expression with several variables? The values for these variables are placed in a list that needs to be passed into the expression.
Your revised question is straightforward, simply
f ## {a,b,c,...} == f[a,b,c,...]
where ## is shorthand for Apply. Internally, {a,b,c} is List[a,b,c] (which you can see by using FullForm on any expression), and Apply just replaces the Head, List, with a new Head, f, changing the function. The operation of Apply is not limited to lists, in general
f ## g[a,b] == f[a,b]
Also, look at Sequence which does
f[Sequence[a,b]] == f[a,b]
So, we could do this instead
f[ Sequence ## {a,b}] == f[a,b]
which while pedantic seeming can be very useful.
Edit: Apply has an optional 2nd argument that specifies a level, i.e.
Apply[f, {{a,b},{c,d}}, {1}] == {f[a,b], f[c,d]}
Note: the shorthand for Apply[fcn, expr,{1}] is ###, as discussed here, but to specify any other level description you need to use the full function form.
A couple other ways...
Use rule replacement
f /. Thread[{a,b} -> l]
(where Thread[{a,b} -> l] will evaluate into {a->1, b->2})
Use a pure function
Function[{a,b}, Evaluate[f]] ## l
(where ## is a form of Apply[] and Evaluate[f] is used to turn the function into Function[{a,b}, a^2+b^2])
For example, for two elements
f[l_List]:=l[[1]]^2+l[[2]]^2
for any number of elements
g[l_List] := l.l
or
h[l_List]:= Norm[l]^2
So:
Print[{f[{a, b}], g[{a, b}], h[{a, b}]}]
{a^2 + b^2, a^2 + b^2, Abs[a]^2 + Abs[b]^2}
Two more, just for fun:
i[l_List] := Total#Table[j^2, {j, l}]
j[l_List] := SquaredEuclideanDistance[l, ConstantArray[0, Length[l]]
Edit
Regarding your definition
f[{__}] = a ^ 2 + b ^ 2;
It has a few problems:
1) You are defining a constant, because the a,b are not parameters.
2) You are defining a function with Set, Instead of SetDelayed, so the evaluation is done immediately. Just try for example
s[l_List] = Total[l]
vs. the right way:
s[l_List] := Total[l]
which remains unevaluated until you use it.
3) You are using a pattern without a name {__} so you can't use it in the right side of the expression. The right way could be:
f[{a_,b_}]:= a^2+b^2;

Resources