I come from a C/C++ background and am trying to understand how are predicates/assertions run/checked in Alloy.
(a) If I have more than one predicates and I want to run both of them, when I run the first predicate how do I ensure that the conditions related to constraint in my other predicate remain static? I am simply puzzled on how do you run multiple predicates.
(b) Same for assertions. Do I have to run check of each assertion?
Thanks for any feedback on this.
You can have an arbitrary formula in your "run" commands, so in there you can conjoin as many predicates as you want. Here is an example:
one sig S {
x: Int
}
pred gt[n: Int] { S.x > n }
pred lt[n: Int] { S.x < n }
run { gt[2] and lt[4] }
With assertions, I think you have to check them one by one, e.g.,
one sig S {
x: Int
}
assert plus_1 { plus[S.x, 1] > S.x }
assert minus_1 { minus[S.x, 1] < S.x }
check plus_1
check minus_1
// doesn't compile: check { plus_1 and minus_1 }
However, you can turn your assertions into predicates, and then you can form arbitrary formulas from them in the body of a "check" command, e.g.,
one sig S {
x: Int
}
pred plus_1[] { plus[S.x, 1] > S.x }
pred minus_1[] { minus[S.x, 1] < S.x }
check { plus_1 and minus_1 }
Related
for x in strategies {
let mut flag = true;
for y in x {
if y {
flag = false;
break;
}
}
if flag {
// do something
}
}
I really hate the use of the flag, and it adds unnecessary branch instructions. I am thinking if there is a way that we can execute // do something if the inner loop exit normally and don't do it if it breaks.
In place of the inner loop, you can take the negation of Iterator::any applied over an identity method such as |y| y or std::convert::identity:
for x in strategies {
// if it's not the case that any are true
if !x.into_iter().any(|y| y) {
// do something
}
}
Equivalently, you can take Iterator::all applied over a negating method such as |y| !y or <bool as std::ops::Not>::not:
use std::ops::Not;
for x in strategies {
// if it is the case that all are false
if x.into_iter().all(Not::not) {
// do something
}
}
Either way, if x is already an Iterator, then the call to .into_iter() is superfluous and can be omitted.
I need to get the "calling" list size in a Groovy list closure, e.g.:
def foo = [1,2,3,4,5]
def bar = foo.findAll {
someCondition(it)
}.collect {
processElement(it, <self>.size())
}
where <self> is the list resulting from filtering foo with findAll.
Of course, one can save the intermediate result and get its size, but is it possible to do without it?
The best I can currently think of is:
def bar = foo.findAll { someCondition(it) }
.with { list ->
list.collect { processElement(it, list.size()) }
}
But this just uses with instead of an intermediate result.
Or, you could use the delegate of a Closure:
def foo = [1,2,3,4,5]
def collector = { it -> processElement(it, delegate.size()) }
(collector.delegate = foo.findAll { someCondition(it) }).collect collector
But this is just using the delegate as an intermediate result ;-)
It's not critical but I was wondering. Somewhere in my program I have a switch statement that gets called multiple times with an incremented value, so that all cases should be executed in order. Something like a custom made simple sequencer.
like this:
private function sequence_Crush(step:Int):Void
{
switch(step) {
case 1: {
action_loadCueFile();
seq.next(); //This calls the same function with an increased step
}
case 2: {
action_saveSettings();
seq.next();
}
/// EDIT: Some steps run ASYNC and an event triggers the next step in the sequence
/// like this:
case 3: {
events.once(ENGINE_EVENTS.cut_all_complete, seq.next);
cutTracks();
}
My Question is, Is there any way to replace the manually written numbers (1,2,3,4) on the cases and use a counter somehow, macros maybe? I have tried putting a dynamic counter, but the Haxe compiler complains.
What I tried:
var st:Int = 1;
switch(step) {
case (st++): { // 1
action_loadCueFile();
seq.next();
}
case (st++): { // 2
action_saveSettings();
seq.next();
}
//... etc
Build halted with errors (haxe.exe)
Case expression must be a constant value or a pattern, not an arbitrary expression
I am targeting JS and using Haxe 3.1.3. I have tried that in actionscript and javascript and it works fine. The reason I want to do that, is that if I want do add or remove a step, I have to re-organize manually every other case number.
p.s. I know there are other ways to sequence actions in order, but I like this one, as I have everything in one function and it's easy to see the order of execution in one glance
Thanks for reading :-)
Jason beat me to it by a few minutes...
Case expressions in Haxe must be either constant values or patterns.
But you can accomplish the desired behaviour in a few ways: (a) custom syntax like $next with macros; (b) macro conversion into if-else blocks (Jason's answer); (c) without macros and (mis)using pattern guards.
Custom syntax
A quick and dirty implementation of it follows; it only supports case $next: and there are no syntax checks.
When a case $next: is found, the macro checks if the previous case pattern was a single constant integer i and, in that case, rewrites the pattern to the value of i + 1.
Macro implementation:
// SequenceSwitch.hx
import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.ExprTools;
class SequenceSwitch {
public
macro static function build():Array<Field> {
var fields = Context.getBuildFields();
for (f in fields)
switch (f.kind) {
case FFun(func) if (func.expr != null):
func.expr = ExprTools.map(func.expr, transf);
case _:
}
return fields;
}
static function transf(e:Expr):Expr {
return switch (e.expr) {
case ESwitch(expr, cases, def):
var ncases = [];
var prev:Array<Expr> = null;
for (c in cases) {
var cur = switch (c.values) {
case [{ expr : EConst(CIdent("$next")), pos : pos }] if (prev != null):
switch (prev) {
case [{ expr : EConst(CInt(i)) }]:
var next = { expr : EConst(CInt(Std.string(Std.parseInt(i) + 1))), pos : pos };
{ values : [next], guard : c.guard, expr : c.expr };
case _:
c;
}
case _:
c;
};
ncases.push(cur);
prev = cur.values;
}
{ expr : ESwitch(expr, ncases, def), pos : e.pos };
case _:
e;
}
}
}
Usage example:
// Text.hx
#:build(SequenceSwitch.build())
class Test {
static function main() {
sequenceCrush(1);
}
static function sequenceCrush(step:Int) {
switch (step) {
case 1:
trace("do one");
sequenceCrush(++step);
case $next:
trace("do two");
sequenceCrush(++step);
case $next:
trace("do three");
sequenceCrush(++step);
case _:
trace("terminate");
}
}
}
No macros/with guards
Similar behaviour could be achieved by (mis)using guards:
static function sequenceCrush_guards(step:Int) {
var st = 1;
switch (step) {
case next if (next == st++):
trace("do one");
sequenceCrush_guards(++step);
case next if (next == st++):
trace("do two");
sequenceCrush_guards(++step);
case next if (next == st++):
trace("do three");
sequenceCrush_guards(++step);
case _:
trace("terminate");
}
}
In Haxe 3 switch changed from the JS/Flash style simple matching, which was really not much more than a chain of if/elseif/else statements, to full on pattern matching, which has many more compile-time features, and one of those limitations is that you can't match against a variable, only against constants.
You could use a chain of if (step==st++) {} elseif (step==st++) {} else {} statements for pretty much the same effect. If you're really really addicted to the switch syntax, you could use a macro to get the "classic" switch behaviour. I happened to write one such macro some time ago, take a look at this GIST:
https://gist.githubusercontent.com/jasononeil/5429516/raw/ad1085082530760aa394765d5cd5ebd61a5dbecb/ClassicSwitch.hx
You could then code like this:
class Action
{
static function main()
{
for (currentStep in 0...5) {
var i = 0;
ClassicSwitch.from(switch (currentStep) {
case i++: trace( 'Do step $i' );
case i++: trace( 'Do step $i' );
case i++: trace( 'Do step $i' );
case i++: trace( 'Do step $i' );
case i++: trace( 'Do step $i' );
});
}
}
}
Which gives me the output:
Action.hx:14: Do step 1
Action.hx:15: Do step 2
Action.hx:16: Do step 3
Action.hx:17: Do step 4
Action.hx:18: Do step 5
If all (or most) of your actions are simple function calls you can alternatively use an array of functions:
var actions = [sequence_Crush.bind(1), // if you want to avoid action index = step - 1
action_loadCueFile,
action_saveSettings,
...];
private function sequence_Crush(step:Int):Void
{
while (step < actions.length)
{
actions[step++]();
}
}
You could also keep this recursive (actions[step++](); if (step < actions.length) { sequence_Crush(step)).
I'm trying to work with these methods with no success and i`ll be happy if someone can help me.
I'm using groovy and i have 2 maps of strings.
I want to match between the strings of the 2 maps with threads (using by gpars)
For example :
def firstMap = ["a":"A", "b":"B"]
def secondMap = ["c":"C", "a":A"]
The normal way to equale between the maps is to
fistMap.findAll().each { first ->
secondMap.findAll.each { second ->
if (first.key.equals(second.key) && (first.value.equlas(second.value))
//saveItIntoArray
}
}
I want to do it with gpars thread so i tried :
withPool(2) {
runForkJoin(firstMap) { task ->
task.each {
secondMap.each {
//equals
}
forChild(?)
}
}
}
I kind of new with this and i really don't know how to make it work.
I will appreciate any help.
Thanks,
Or.
What I'd suggest is using parallel collections:
def firstMap = ["a":"A", "b":"B"]
def secondMap = ["c":"C", "a":"A"].asImmutable()
withPool{
println firstMap.findAllParallel { fk, fv -> secondMap.findResult { sk, sv -> fk == sk && fv == sv ? [(fk):fv] : null } }
}
It would seem that GPathResult returns a list of nodes which is the same for each iteration. How can I insert nodes from one iteration and find them in the next, as shown in the example below?
def messageNodes = [] as HashSet
def inputRoot = new XmlSlurper().parse(xmlFile)
inputRoot.testsuite.list().each { suiteNode ->
suiteNode.children().list().each { caseNode ->
caseNode.children().list().each { messageNode ->
messageNodes << messageNode
}
}
}
inputRoot.testsuite.list().each { suiteNode ->
suiteNode.children().list().each { caseNode ->
caseNode.children().list().each { messageNode ->
assert messageNodes.contains(message)
}
}
}
That code isn't inserting nodes... But as it stands (trying to find nodes are the same between scans), it won't work either due to the way XmlSlurper works...
When you call children() on a GPathResult, you end up with an iterator that returns new instances of NodeChild. Because these are new instances, they cannot be compared to the last time you saw them (as their hashcode will be different)
If you change your code to use XmlParser like so:
def messageNodes = []
def inputRoot = new XmlParser().parse(xmlFile)
inputRoot.testsuite.'*'.'*'.each { messageNode ->
messageNodes << messageNode
}
inputRoot.testsuite.'*'.'*'.each { messageNode ->
println messageNode.hashCode()
assert messageNodes.contains(messageNode)
}
I believe it works as you'd expect (I had to guess at your xml format though, as you didn't show us what it was in the question)
As an addition, you can change the lines
inputRoot.testsuite.'*'.'*'.each { messageNode ->
messageNodes << messageNode
}
to
messageNodes.addAll( inputRoot.testsuite.'*'.'*' )
for the same functionality...
It should also be noted that XmlSlurper doesn't store internal state in a navigable way, so if you add nodes, you cannot find them unless you write the xml out and read it back in. If this is the sort of thing you're aiming for, XmlParser is probably also the better route