xor operation in Alloy - alloy

Is there an xor operation in alloy, if not, how can I define it:
I would like to have a predicate named xor that gets two predicates as argument and it holds true when their xor hold true.
more elaborately, if I have P1 and P2, I know that I can have P3 defined as bellow:
pred P3(){
(P1 and (not P2)) or ((not P1) and P2)
}
to be an xor of P1 and P2, but I want to define xor (or any other formula connectives), put it in a library and use them later. so I would like my P3 get predicates as the argument. Is this possible?
thanks

The xor operation can just be written as iff not.

Alloy has unfortunately no Boolean type. Without a proper type, you can't declare arguments for your predicate. Your approach seems thus a lost cause.
I can think of two ugly tricks both involving the use of util/boolean or your own Boolean definition to make things work.
In both tricks your XOR predicate shall take two Bool arguments.
pred xor[ x,y:Bool){
x != y
}
In the first trick, represent all your propositions as singleton signatures(e.g. P1 and P2) rather than predicates. Have those signatures declare a Bool typed field (e.g. bool) and set this field in a signature fact using the formula you would put in your predicate P1 and P2.
call then your predicate xor as follows :
xor[P1.bool ,P2.bool]
In the second trick
you keep your propositions represented as predicates (P1 and P2), but when calling xor, you'll need to "cast" the truth value of those predicates to Bool.
xor[(P1 implies True else False ),(P2 implies True else False )]
Again in my opinion both solutions are ugly. It would be nice to have a broader view of what you would like to achieve in order to come with a better solution.

Related

Are Haskell guards evaluated sequentially?

What is the order in which Haskell guards are evaluated?
Say that I have a function which returns a Bool:
someFunc :: Bool -> Bool -> Bool
someFunc b1 b2
| b1 == True && b2 == True = True
| b1 == True = False
| b1 == False .....
...
I think it was with Monads and the Do-notation that I read, that actions are sometimes not evaluated sequentially. That is if I have:
do { val1 <- action1
val2 <- action2
action3 }
It might be the case that val2 will be calculated before val1.
Is this the case for guards as well? Can they be evaluated out of order?
If guards were sequential, then if the first statement evaluates to False, and the second evaluates to True, then I can conclude that b2 is False. Does this logic always hold?
Edit: By statements I mean guard 1 to 3
Evaluating the tests within guards can’t have any side-effects — unlike in procedural languages. So the order of evaluating the comparisons or Boolean connectives doesn’t make any difference to the semantics of the program.
Prioritising the branches — that is, each of the lines starting | — is from top to bottom. But really ‘evaluating’ is the wrong concept: it would be OK for the compiler to first evaluate your b1 == False, providing it didn’t take the third branch until it had checked the first two. (GHC doesn’t actually do that; I’m just setting up a straw man.)
Note that in a call to someFunc, the arguments for b1, b2 might be arbitrarily complex expressions. Haskell’s ‘Lazy semantics’ mean that neither of them are evaluated until needed.
Does this logic always hold?
Be careful: if an early guard turns out False, you can’t assume anything about the expressions in it. The compiler might have rearranged them for efficiency, evaluated one out of textual order, then moved on. In your example, if for the first branch it turned out b1 /= True, the compiler might not evaluate b2 at all. So you can’t conclude anything about b2. Indeed b2 might give bottom/infinite calculation, if evaluated.
It’s not just with Monads or Do-notation (which are the same thing) that expressions are not necessarily evaluated in textual order — that’s true across any expressions in any context. (The IO Monad has some dodgy semantics, to make it seem ‘statements’ are executed top-to-bottom.)

In what logical sense is Haskell referentially transparent?

Haskell is sometimes said to "replace equals for equals". The following code shows this isn't true under every interpretation of such a sentence. Wikipedia follows that by saying f(x)=f(x) for every x but that doesn't seem to carry any actual logical content one can test, it would be true by the reflexive law, a tautology.
I think the phrasing needed to make a logical claim like this is more like Leibniz' law (or indistinguishable identicals) where
x=y implies for every f, f(x)=f(y). That claim fails in the illustration below within Haskell. (We override == to make a partition type, but our function definition can freely ignore this and do.)
My question is, can one actually state referential transparency in a way that can be logically tested, and does Haskell actually uphold that logical claim?
module Main (main) where
data Floop = One | Two | Three
instance Eq Floop where
One == One = True
One == Two = False
One == Three = False
Two == One = False
Two == Two = True
Two == Three = True --- 2=3
Three == One = False
Three == Two = True --- 3=2
Three == Three = True
shuffle :: Floop -> Floop
shuffle One = Two
shuffle Two = Two --- fix 2
shuffle Three = One --- move 3
main = print ( (Two == Three) && (shuffle Two /= shuffle Three) )
--- prints "True" proving Haskell violates Leibniz Law
Expanding slightly on what I already said in my comment (thanks #FyodorSolkin for the prod):
You haven't violated referential transparency there, you've just made a pathological Eq instance.
While, as you've observed, the language doesn't forbid you from doing this, nor does it forbid one from making unlawful Functor or Monad instances. (Because it would be totally unfeasible to try to check these laws in practice.) But just because something doesn't cause a compiler error doesn't necessarily mean it's the right thing to do.
So the problem with your example is that while, semantically, (==) in Haskell indeed means "equal", it's just a function, in fact a method of a typeclass - which you can therefore implement however you want. Nothing stops me from defining, for example:
instance (Eq) (a -> b) where
_ == _ = True
and suddenly all functions will be considered "equal" under this definition. Clearly referential transparency will be violated if we consider this to be a true definition of equality. My point is that it's not. In fact it's quite obvious what "equality" means for any type which isn't either a function or otherwise depends on or "contains" function types. (It's actually obvious what equality of functions should mean too, it's just impossible for there to be a general algorithm to determine if two arbitrary functions are equal.)
[EDIT: I just remembered it also doesn't make much sense to talk about equality of IO actions. There might be some other abstract types like that where there's no clear definition of what equality would mean.]
To stray into abstract mathematics for a minute: your Eq instance certainly defines an equivalence relation, which is considered to be a sort of "generalised equality" - and indeed is equality if you use the relation to make equivalence classes. But then it's nonsense to try to apply a function to such a domain/type which differs on different elements of the same equivalence class. Such a thing - as in your example - actually fundamentally fails to be a well-defined mathematical function, because you're defining it on the individual elements in a way which fails to respect the equivalence relation.
f(x)=f(x) for every x
is by no means a tautology. In many popular languages, this property does not hold. Consider Java, for instance:
import java.util.*;
public class Transparency {
static int f(List<Object> xs) {
xs.add(xs.size());
return xs.size();
}
public static void main(String[] args) {
List<Object> x = new ArrayList<>();
System.out.println("Is java referentially transparent? " + (f(x) == f(x)));
}
}
$ javac Transparency.java
$ java Transparency
Is java referentially transparent? false
Here, because f mutates its input x, it would change behavior if we substitute x's definition into f(x) == f(x): f(new ArrayList<>()) == f(new ArrayList<>()) is in fact true, but when using a variable to reduce duplication it evaluates to false. In Haskell, such a substitution is always valid (disregarding cheats like unsafePerformIO).

How to interpret this discussion of Verilog relational operators

This discussion of Verilog relational operators at ASIC World clearly has at least one mistake:
The result is a scalar value (example a < b)
0 if the relation is false (a is bigger then b)
1 if the relation is true (a is smaller then b)
x if any of the operands has unknown x bits (if a or b contains X)
Note: If any operand is x or z, then the result of that test is
treated as false (0)
Clearly, "a is bigger than b" should be "a is bigger than or equal to b".
There is something else that looks wrong to me, but I don't know if it's just because I'm a Verilog novice. The last bullet point seems to contradict the subsequent note, unless there is a difference between an operand having all unknown bits (in which case the result of a relational operator will be x) and an operand being x (in which case the result will be 0).
Is there a difference between an operand being x and all of its bits being X? I know Verilog is case-sensitive.
verilog is known for its x-propagation pessimism.
From lrm 11.4.4
An expression using these relational operators shall yield the scalar value 0 if the specified relation is false
or the value 1 if it is true. If either operand of a relational operator contains an unknown (x) or highimpedance
(z) value, then the result shall be a 1-bit unknown value (x).
so, if any of the values contains 'x' bits the result will be 'x'.
Now in case, when the result is used as a conditional expression, the if statement will take true brunch if and only if the result is '1'. Otherwise it will take the false branch. Also, there are conversion rules in verilog, where x and z values are converted to 0 in binary operations, which conditional operation is.
so, the comment on the site is correct, it is talking of the results of a test (as in if statement)
If any operand is x or z, then the result of that test is treated as false (0)
I think you should take your comments to the author of that website.
I take the statement inside the ()'s to be an example
1 if the relation is true (if for example, a is smaller then b)
The subsequent note refers to a more general issue not specific to relational operators. When you have
if (expression) true_statement; else false_statement;
When expression evaluates to an X or 0, the false_statement branch is taken.
Also, Verilog is not case sensitive about numeric literals. 'habcxz and 'hABCXZ are equivalent.

Defining a function by equations with different number of arguments

I noticed today that such a definition
safeDivide x 0 = x
safeDivide = (/)
is not possible. I am just curious what the (good) reason behind this is. There must be a very good one (it's Haskell after all :)).
Note: I am not looking suggestions for alternative implementations to the code above, it's a simple example to demonstrate my point.
I think it's mainly for consistency so that all clauses can be read in the same manner, so to speak; i.e. every RHS is at the same position in the type of the function. I think would mask quite a few silly errors if you allowed this, too.
There's also a slight semantic quirk: say the compiler padded out such clauses to have the same number of patterns as the other clauses; i.e. your example would become
safeDivide x 0 = x
safeDivide x y = (/) x y
Now consider if the second line had instead been safeDivide = undefined; in the absence of the previous clause, safeDivide would be ⊥, but thanks to the eta-expansion performed here, it's \x y -> if y == 0 then x else ⊥ — so safeDivide = undefined does not actually define safeDivide to be ⊥! This seems confusing enough to justify banning such clauses, IMO.
The meaning of a function with multiple clauses is defined by the Haskell standard (section 4.4.3.1) via translation to a lambda and case statement:
fn pat1a pat1b = r1
fn pat2a pat2b = r2
becomes
fn = \a b -> case (a,b) of
(pat1a, pat1b) -> r1
(pat2a, pat2b) -> r2
This is so that the function definition/case statement way of doing things is nice and consistent, and the meaning of each isn't specified redundantly and confusingly.
This translation only really makes sense when each clause has the same number of arguments. Of course, there could be extra rules to fix that, but they'd complicate the translation for little gain, since you probably wouldn't want to define things like that anyway, for your readers' sake.
Haskell does it this way because it's predecessors (like LML and Miranda) did. There is no technical reason it has to be like this; equations with fewer arguments could be eta expanded. But having a different number of arguments for different equations is probably a typo rather than intentional, so in this case we ban something sensible&rare to get better error reporting in the common case.

Update2,Haskell

Atom: The Atom is the datatype used to describe Atomic Sentences or propositions. These are basically
represented as a string.
Literal: Literals correspond to either atoms or negations of atoms. In this implementation each literal
is represented as a pair consisting of a boolean value, indicating the polarity of the Atom, and the
actual Atom. Thus, the literal ‘P’ is represented as (True,"P") whereas its negation ‘-P’ as
(False,"P").
2
Clause: A Clause is a disjunction of literals, for example PvQvRv-S. In this implementation this
is represented as a list of Literals. So the last clause would be [(True,"P"), (True,"Q"),
(True,"R"),(False,"S")].
Formula: A Formula is a conjunction of clauses, for example (P vQ)^(RvP v-Q)^(-P v-R).
This is the CNF form of a propositional formula. In this implementation this is represented as a list of
Clauses, so it is a list of lists of Literals. Our above example formula would be [[(True,"P"),
(True,"Q")], [(True,"R"), (True,"P"), (False,"Q")], [(False, "P"),
(False,"P")]].
Model: A (partial) Model is a (partial) assignment of truth values to the Atoms in a Formula. In this
implementation this is a list of (Atom, Bool) pairs, ie. the Atoms with their assignments. So in the
above example of type Formula if we assigned true to P and false to Q then our model would be
[("P", True),("Q", False)]
Ok so I wrote and update function
update :: Node -> [Node]
It takes in a Node and returns a list of the Nodes
that result from assigning True to an unassigned atom in one case and False in the other (ie. a case
split). The list returned has two nodes as elements. One node contains the formula
with an atom assigned True and the model updated with this assignment, and the other contains
the formula with the atom assigned False and the model updated to show this. The lists of unassigned
atoms of each node are also updated accordingly. This function makes use of an
assign function to make the assignments. It also uses the chooseAtom function to
select the literal to assign.
update :: Node -> [Node]
update (formula, (atoms, model)) = [(assign (chooseAtom atoms, True) formula, (remove (chooseAtom atoms) atoms, ((chooseAtom atoms,True)) `insert` model)) , (assign (chooseAtom atoms, False) formula, (remove (chooseAtom atoms) atoms, ((chooseAtom atoms, False) `insert` model)) )]
Now I have to do the same thing but this time I must implement a variable selection heuristic.this should replace the chooseAtom and I'm supposed to write a function update2 using it
type Atom = String
type Literal = (Bool,Atom)
type Clause = [Literal]
type Formula = [Clause]
type Model = [(Atom, Bool)]
type Node = (Formula, ([Atom], Model))
update2 :: Node -> [Node]
update2 = undefined
So my question is how can I create a heurestic and to implement it into the update2 function ,that shoud behave identical to the update function ?
If I understand the question correctly, you're asking how to implement additional selection rules in resolution systems for propositional logic. Presumably, you're constructing a tree of formulas gotten by assigning truth-values to literals until either (a) all possible combinations of assignments to literals have been tried or (b) box (the empty clause) has been derived.
Assuming the function chooseAtom implements a selection rule, you can parameterize the function update over an arbitrary selection rule r by giving update an additional parameter and replacing the occurrence of chooseAtom in update by r. Since chooseAtom implements a selection rule, passing that selection rule to the parameter r gives the desired result. If you provide an implementation of chooseAtom and the function you intend to replace it, it would be easier to verify that your implementation is correct.
Hopefully this is helpful. However, it's unclear exactly what's being asked. In particular, you're asking for a "variable selection rule." However, it looks like you're implementing a resolution system for propositional logic. In general, selection rules and variables are associated with resolution for predicate logic.

Resources