Variable-Value pairs (i.e., maps) are not retained when one of them gets nullified - alloy

I have the following simple model where I try to simulate the nullification of a select Data from a Dataset. Data to Val (d2v) mapping is a field of a signature called Dynamic whose instances correspond to different states of the model (before and after). When I try to simulate this model, I get two unrelated Dynamic instances, even though I explicitly set the d2v mappings of the two Dynamic instances to be the same (except of course the mapping of Data instance being passed to nullify predicate). In other words, the variable-value pairings of the two instances of Dynamic do not match. What am I missing?
sig Data {}
sig Val {}
sig Dynamic {
d2v: Data -> lone Val,
}
pred nullify [dyn, dyn': Dynamic, d:Data] {
d in dyn.d2v.univ implies
dyn'.d2v = dyn.d2v - (d -> d.(dyn.d2v))
else
dyn'.d2v = dyn.d2v
}
run nullify for exactly 3 Data,
exactly 3 Val,
exactly 2 Dynamic
Here is an example evaluation of the two instances of Dynamic.d2v from Alloy:
sig Dynamic
Dynamic$0
field d2v
Data$2 -> Val$2
Dynamic$1
field d2v
Data$0 -> Val$1
Data$1 -> Val$0
where Data$2 is the argument of remove predicate. What I would expect, for instance, is the following:
sig Dynamic
Dynamic$0
field d2v
Data$2 -> Val$2
Data$0 -> Val$1
Data$1 -> Val$0
Dynamic$1
field d2v
Data$0 -> Val$1
Data$1 -> Val$0

Are you sure that the instance binds dyn and dyn' to Dynamic$0 and Dynamic$1? It could bind them both to Dynamic$1 for example, satisfying the else arm of your predicate.

Related

A meaningful field name for the ternary relation between program, data, and result?

I have a signature for representing software programs:
sig Program {
???: Data -> Result
}
Each program maps input data to output result. So, there is a ternary relation (Program -> Data -> Result).
Notice the question marks for the field name. What field name do you suggest?
The name IO seems nice:
sig Program {
IO: Data -> Result
}
Then I can write elegant expressions such as:
all p: Program | p.IO ...
However, the name IO is meaningful only for (Data -> Result) not (Program -> Data -> Result).
I am stuck. What do you suggest?
IMHO, fields' names are most of the time contextual to the signature they are declared in, and that's really a fine thing.
If you look at a random sample module in Alloy, (e.g. module examples/puzzle/farmer), you'll see that it's not always that fields have meaning outside of their respective signatures:
sig State {
near: set Object,
far: set Object
}
Here, near and far don't really convey hints on their "temporal" nature.
Long story short, I'd stick to io for conciseness sake.
Indeed, I prefer the names of :
fiels, facts, preds, asserts, parameters, .. to be in lowercase
signatures to be Capitalized
enumeration (outer let), and singleton signatures to be in UPPERCASE

Checking Haskell typeclasses in a function

If I wanted to perform a search on a problem space and I wanted to keep track of different states a node has already visited, I several options to do it depending on the constraints of those states. However; is there a way I can dispatch a function or another depending on the constraint of the states the user is using as input? For example, if I had:
data Node a = Node { state :: a, cost :: Double }
And I wanted to perform a search on a Problem a, is there a way I could check if a is Eq, Ord or Hashable and then call a different kind of search? In pseudocode, something like:
search :: Eq a => Problem a -> Node a
search problem#(... initial ...) -- Where initial is a State of type a
| (Hashable initial) = searchHash problem
| (Ord initial) = searchOrd problem
| otherwise = searchEq problem
I am aware I could just let the user choose one search or another depending on their own use; but being able to do something like that could be very handy for me since search is not really one of the user endpoints as such (one example could be a function bfs, that calls search with some parameters to make it behave like a Breadth-First Search).
No, you can't do this. However, you could make your own class:
class Memorable a where
type Memory a
remember :: a -> Memory a -> Memory a
known :: a -> Memory a -> Bool
Instantiate this class for a few base types, and add some default implementations for folks that want to add new instances, e.g.
-- suitable implementations of Memorable methods and type families for hashable things
type HashMemory = Data.HashSet.HashSet
hashRemember = Data.HashSet.insert
hashKnown = Data.HashSet.member
-- suitable implementations for orderable things
type OrdMemory = Data.Set.Set
ordRemember = Data.Set.insert
ordKnown = Data.Set.member
-- suitable implementations for merely equatable things
type EqMemory = Prelude.[]
eqRemember = (Prelude.:)
eqKnown = Prelude.elem

Alloy - Count atoms used by other atoms

I'm trying to notice a change in atom relations to other atoms. Using the below signatures :
sig Word, Definition{}
sig Dictionary {
def: Word -> lone Definition
}
I then use a predicate to show what happens when you add a new relation to a Dictionary by having another Dictionarywhich is the same but with one more relation.
pred addRelation [d,d':Dictionary,w:Word,f:Definition] {
d'.word = d.word + w -> f
}
To see if the number of Word atoms used by the first Dictionary increase I can show only the instances where this occurs using:
#d'.def.Definition > #d.def.Definition
However, is there a way to see if the number of Definition atoms used by the second Dictionary atom has increased? I've been using trial and error in the Alloy Evaluator to try and find a value for this but have come up short.
Thanks!
Like this?
sig Word, Definition{}
sig Dictionary {
def: Word -> lone Definition
}
pred addRelation [d,d':Dictionary,w:Word,f:Definition] {
d'.def = d.def + w -> f
#d'.def[Word] > #d.def[Word]
}
run addRelation

specifying properties of relations in alloy

I am trying to express certain mathematical properties of relations in Alloy, but I am not sure if I have the right approach yet, as I am just a beginner. Would appreciate any insights from the community of experts out there!
Specifying the fact that domain of a relation as singleton. e.g. Is the following a reasonable and correct way to do that?
pred SingletonDomain(r: univ->univ) {
one ~r
}
sig S2 {}
sig S1 {
child: set S2
}
fact {
SingletonDomain [child]
}
or should it be something like the following
pred SingletonDomain (r: univ->univ) {
#S2.~r = 1
}
This is not very modular since the use of S2 is very specific to the particular signature.
Specifying the fact that a relation is a total order. At the moment I am using the following, basically I am simulating xor
pred total[r: univ->univ] {
all disj e, e': Event | (e.r = e' and e'.r != e) or (e.r != e' and e'.r = e)
}
Thanks
To specify the fact that the domain of a given relation is a singleton, your first attempt is really close to do the trick. The only problem is that one ~r enforces the inverse of the r relation (and thus the r relation itself) to be composed of a single tuple. This is not what you want to express.
What you want to express is that all elements in the range of the r relation have the same (so only one) image through its inverse relation '.
You should thus write the following predicate :
pred SingletonDomain(r: univ->univ) {
one univ.~r
}
For your second question, your predicate doesn't handle cases were e -> e' -> e '' -> e. To handle those, you can use transitive closure.

"Strategy Pattern" in Haskell

In the OO world, I have a class (let's call it "Suggestor") that implement something approaching a "Strategy Pattern" to provide differing implementations of an algorithm at runtime. As an exercise in learning Haskell, I want to rewrite this.
The actual use-case is quite complex, so I'll boil down a simpler example.
Let's say I have a class Suggester that's takes a list of rules, and applies each rule as a filter to a list of database results.
Each rule has three phases "Build Query", "Post Query Filter", and "Scorer". We essentially end up with an interface meeting the following
buildQuery :: Query -> Query
postQueryFilter :: [Record] -> [Record]
scorer :: [Record] -> [(Record, Int)]
Suggestor needs to take a list of rules that match this interface - dynamically at run time - and then execute them in sequence. buildQuery() must be run across all rules first, followed by postQueryFilter, then scorer. (i.e. I can't just compose the functions for one rule into a single function).
in the scala I simply do
// No state, so a singleton `object` instead of a class is ok
object Rule1 extends Rule {
def buildQuery ...
def postQueryFilter ...
def scorer ...
}
object Rule2 extends Rule { .... }
And can then initialise the service by passing the relevant rules through (Defined at runtime based on user input).
val suggester = new Suggester( List(Rule1, Rule2, Rule3) );
If the rules were a single function, this would be simple - just pass a list of functions. However since each rule is actually three functions, I need to group them together somehow, so I have multiple implementations meeting an interface.
My first thought was type classes, however these don't quite seem to meet my needs - they expect a type variable, and enforce that each of my methods must use it - which they don't.
No parameters for class `Rule`
My second thought was just to place each one in a haskell module, but as modules aren't "First Class" I can't pass them around directly (And they of course don't enforce an interface).
Thirdly I tried creating a record type to encapsulate the functions
data Rule = Rule { buildQuery :: Query -> Query, .... etc }
And then defined an instance of "Rule" for each. When this is done in each module it encapsulates nicely and works fine, but felt like a hack and I'm not sure if this is an appropriate use of records in haskell?
tl;dr - How do I encapsulate a group of functions together such that I can pass them around as an instance of something matching an interface, but don't actually use a type variable.
Or am I completely coming at this from the wrong mindset?
In my opinion your solution isn't the "hack", but the "strategy pattern" in OO languages: It is only needed to work around the limitations of a language, especially in case of missing, unsafe or inconvenient Lambdas/Closures/Function Pointers etc, so you need a kind of "wrapper" for it to make it "digestible" for that language.
A "strategy" is basically a function (may be with some additional data attached). But if a function is truly a first class member of the language - as in Haskell, there is no need to hide it in the object closet.
Just generate a single Rule type as you did
data Rule = Rule
{ buildQuery :: Query -> Query
, postQueryFilter :: [Record] -> [Record]
, scorer :: [Record] -> [(Record, Int)]
}
And build a general application method—I'm assuming such a generic thing exists given that these Rules are designed to operate independently over SQL results
applyRule :: Rule -> Results -> Results
Finally, you can implement as many rules as you like wherever you want: just import the Rule type and create an appropriate value. There's no a priori reason to give each different rule its own type as you might in an OO setting.
easyRule :: Rule
easyRule = Rule id id (\recs -> zip recs [1..])
upsideDownRule :: Rule
upsideDownRule = Rule reverse reverse (\recs -> zip recs [-1, -2..])
Then if you have a list of Rules you can apply them all in order
applyRules :: [Rule] -> Results -> Results
applyRules [] res = res
applyRules (r:rs) res = applyRules rs (applyRule r res)
which is actually just a foldr in disguise
applyRules rs res = foldr applyRule res rs
foo :: Results -> Results
foo = applyRules [Some.Module.easyRule, Some.Other.Module.upsideDownRule]

Resources