Get greater number in a field? Alloy model checker - alloy

I want to return the greater number max(loc.x) in a field scope:
sig Locations{
x: set Int // all x locations visited
xgreater: one Int // greater location
}
fact{all loc:Locations| xgreater = greaterX[loc]} // get greater location
fun greaterX[loc:Locations]:Int{ // get the greater location
max(loc.x) // HOW do I do this?
}
Any ideas? Thank you.

How about making it a predicate
pred greatest [locs: set Location, x: Location] {...}
with a constraint that there is no location in lock larger than the x?
(Note also that I've changed the signature name to Location: as with classes and types, the convention is to use the singular noun.)

Related

Comparator vs Closure in min call in groovy?

I am trying to understand the difference between passing a Closure vs a Comparator to the min function on a collection:
// Example 1: Closure/field/attribute?
Sample min = container.min { it.timespan.start }
// Example 2: Comparator
Sample min2 = container.min(new Comparator<Sample>() {
#Override
int compare(Sample o1, Sample o2) {
return o1.timespan.start <=> o2.timespan.start
}
})
They both return the correct result.
Where:
class Sample {
TimeSpan timespan
static constraints = {
}
}
And:
class TimeSpan {
LocalDate start
LocalDate end
}
In Example 1 I just pass the field timespan.start to min which I guess means that I am passing a Closure (even though its just a field in a class)?
In Example 1 does groovy convert the field timespan.start into a Comparator behind the scenes like the one I create explicitly in Example 2?
The difference is, that those are two different min methods both
taking different arguments. There is one for passing
a closure
and one for the
comparator
(there is a third one using identity and some deprecated ones, but we can ignore that for now).
The first version (Closure with one (implicit argument)) you have to
extract the value from the passed value, you want to make the min
aggregate with. Therefor this versions has some inner working to deal
with comparing the values.
But the docs also state:
If the closure has two parameters it is used like a traditional
Comparator. I.e. it should compare its two parameters for order,
returning a negative integer, zero, or a positive integer when the
first parameter is less than, equal to, or greater than the second
respectively. Otherwise, the Closure is assumed to take a single
parameter and return a Comparable (typically an Integer) which is then
used for further comparison.
So you can use a Closure version also to the same as your second example
(you have to define two params explicitly):
container.min{ a, b -> a <=> b }
And there is also a shorter version of the second example. You can cast
a Closure to an interface with groovy. So this works too:
container.min({ a, b -> a <=> b } as Comparator)

(Swift 4.x+) What are the rules for naming parameters in structs’ initializers?

I have been doing an intense - yet basic apparently - study on structs in these last days and one of the things I cannot understand is why one would ever name parameters in an initializer differently from their original name.
I know that is possible, that it is allowed but, in practice, I have always seen shadowing instead.
For example:
struct Person {
var name: String
var age: Int
init(firstName: String, ancientness: Int) {
self.name = firstName
self.age = ancientness
}
}
Apart from the absurd fun one would have in inventing idiotic names, is there a truly practical reason why one would ever do such a thing?
Thank you
The short answer is no. The long answer is when creating a custom structure you don't even have to provide a custom initializer. The struct will provide it for you. Not related to your question but you should always declare your properties as constants. If you need a different value create a new structure with the values updated from the old instance. Just create a "plain" structure:
struct Person {
let name: String
let age: Int
}
This will provide a the default initializer with the following signature:
Person.init(name: String, age: Int)
If you were gonna provide yourself the same initializer for that structure it would be written as:
init(name: String, age: Int) {
self.name = name
self.age = age
}
the final thoughts
There is no reason to do such thing. You should keep your initializers names matching the name of the properties that they will be assigned to. The only "advantage" of choosing a different name is not having to explicitly call self inside the initializer.
In your example it would suffice
init(firstName: String, ancientness: Int) {
name = firstName
age = ancientness
}
but not on mine
init(name: String, age: Int) {
name = name // Cannot assign to value: 'name' is a 'let' constant
age = age // Cannot assign to value: 'name' is a 'let' constant
}
A Truly practical reason?
The only one I can see is dropping the self which can already be done 99% of the time already when coding in Swift. I actually like a lot to use the shadowing whenever it is possible in all of my answers. You can see it at this post Swift Array instance method drop(at: Int) where a local var indexshadowing the collection method index<T: Comparable>(_ T, offsetBy: T, limitedBy: T).
Or at this post Swift: second occurrence with indexOf a classic shadowing example
var startIndex = self.startIndex
Where you can refer to startIndex local method variable or the collection's instance property adding the self prefix self.startIndex.

Assign an array to a property in a Chapel Class

Here is a Python-like pattern I need to re-create in Chapel.
class Gambler {
var luckyNumbers: [1..0] int;
}
var nums = [13,17,23,71];
var KennyRogers = new Gambler();
KennyRogers.luckyNumbers = for n in nums do n;
writeln(KennyRogers);
Produces the run-time error
Kenny.chpl:8: error: zippered iterations have non-equal lengths
I don't know how many lucky numbers Kenny will have in advance and I can't instantiate Kenny at that time. That is, I have to assign them later. Also, I need to know when to hold them, know when to fold them.
This is a good application of the array.push_back method. To insert lucky numbers one at a time you can do:
for n in nums do
KennyRogers.luckyNumbers.push_back(n);
You can also insert the whole array in a single push_back operation:
KennyRogers.luckyNumbers.push_back(nums);
There are also push_front and insert methods in case you need to put elements at the front or at arbitrary positions in the array.
I don't think I can help on when to hold them or when to fold them.
A way to approach this that simply makes things the right size from the start and avoids resizing/rewriting the array is to establish luckyNumbers in the initializer for Gambler. In order to do this without resizing, you'll need to declare the array's domain and set it in the initializer as well:
class Gambler {
const D: domain(1); // a 1D domain field representing the array's size
var luckyNumbers: [D] int; // declare lucky numbers in terms of that domain
proc init(nums: [?numsD] int) {
D = numsD; // make D a copy of nums's domain; allocates luckyNumbers to the appropriate size
luckyNumbers = nums; // initialize luckyNumbers with nums
super.init(); // mark the initialization of fields as being done
}
}
var nums = [13,17,23,71];
var KennyRogers = new Gambler(nums);
writeln(KennyRogers);

At least one Var equals to X within a Var array using Choco Solver

I'm using Choco Solver and given an array of int vars, I want a constraint that check that at least one var in the array is equal to a static value...
Something similar to IntConstraintFactory#count but with the following doc :
/**
* Let N be the number of variables of the VARIABLES collection assigned to value VALUE;
* Enforce condition N >= LIMIT to hold.
* <p>
*
* #param VALUE an int
* #param VARS a vector of variables
* #param LIMIT a variable
*/
public static Constraint at_least(int VALUE, IntVar[] VARS, IntVar LIMIT) {
return new Constraint("At least", /* help here ? */);
}
Does someone knows if it exists or how I can implement it efficiently ?
If you want to post constraint atLeast(VALUE,VARS, LIMIT) in Choco Solver, you can simply post count(VALUE,VARS,X), with X an IntVar of initial domain [0,VARS.length], and post arithm(X,">=",LIMIT). This will do the job. There is no need of implementing a specific constraint for that.
If you want to check that at least one variable in VARS is equal to VALUE, it is even simpler, simply post count(VALUE, VARS, X) with [1,VARS.length] as the initial domain for X. So the minimal number of occurrence of VALUE will be at least 1. No need to create a second variable and the arithmetic constraint.

Inconsistencies when using UnsafeMutablePointer with String or Character types

I'm currently trying to implement my own DynamicArray data type in Swift. To do so I'm using pointers a bit. As my root I'm using an UnsafeMutablePointer of a generic type T:
struct DynamicArray<T> {
private var root: UnsafeMutablePointer<T> = nil
private var capacity = 0 {
didSet {
//...
}
}
//...
init(capacity: Int) {
root = UnsafeMutablePointer<T>.alloc(capacity)
self.capacity = capacity
}
init(count: Int, repeatedValue: T) {
self.init(capacity: count)
for index in 0..<count {
(root + index).memory = repeatedValue
}
self.count = count
}
//...
}
Now as you can see I've also implemented a capacity property which tells me how much memory is currently allocated for root. Accordingly one can create an instance of DynamicArray using the init(capacity:) initializer, which allocates the appropriate amount of memory, and sets the capacity property.
But then I also implemented the init(count:repeatedValue:) initializer, which first allocates the needed memory using init(capacity: count). It then sets each segment in that part of memory to the repeatedValue.
When using the init(count:repeatedValue:) initializer with number types like Int, Double, or Float it works perfectly fine. Then using Character, or String though it crashes. It doesn't crash consistently though, but actually works sometimes, as can be seen here, by compiling a few times.
var a = DynamicArray<Character>(count: 5, repeatedValue: "A")
println(a.description) //prints [A, A, A, A, A]
//crashes most of the time
var b = DynamicArray<Int>(count: 5, repeatedValue: 1)
println(a.description) //prints [1, 1, 1, 1, 1]
//works consistently
Why is this happening? Does it have to do with String and Character holding values of different length?
Update #1:
Now #AirspeedVelocity addressed the problem with init(count:repeatedValue:). The DynamicArray contains another initializer though, which at first worked in a similar fashion as init(count:repeatedValue:). I changed it to work, as #AirspeedVelocity described for init(count:repeatedValue:) though:
init<C: CollectionType where C.Generator.Element == T, C.Index.Distance == Int>(collection: C) {
let collectionCount = countElements(collection)
self.init(capacity: collectionCount)
root.initializeFrom(collection)
count = collectionCount
}
I'm using the initializeFrom(source:) method as described here. And since collection conforms to CollectionType it should work fine.
I'm now getting this error though:
<stdin>:144:29: error: missing argument for parameter 'count' in call
root.initializeFrom(collection)
^
Is this just a misleading error message again?
Yes, chances are this doesn’t crash with basic inert types like integers but does with strings or arrays because they are more complex and allocate memory for themselves on creation/destruction.
The reason it’s crashing is that UnsafeMutablePointer memory needs to be initialized before it’s used (and similarly, needs to de-inited with destroy before it is deallocated).
So instead of assigning to the memory property, you should use the initialize method:
for index in 0..<count {
(root + index).initialize(repeatedValue)
}
Since initializing from another collection of values is so common, there’s another version of initialize that takes one. You could use that in conjunction with another helper struct, Repeat, that is a collection of the same value repeated multiple times:
init(count: Int, repeatedValue: T) {
self.init(capacity: count)
root.initializeFrom(Repeat(count: count, repeatedValue: repeatedValue))
self.count = count
}
However, there’s something else you need to be aware of which is that this code is currently inevitably going to leak memory. The reason being, you will need to destroy the contents and dealloc the pointed-to memory at some point before your DynamicArray struct is destroyed, otherwise you’ll leak. Since you can’t have a deinit in a struct, only a class, this won’t be possible to do automatically (this is assuming you aren’t expecting users of your array to do this themselves manually before it goes out of scope).
Additionally, if you want to implement value semantics (as with Array and String) via copy-on-write, you’ll also need a way of detecting if your internal buffer is being referenced multiple times. Take a look at ManagedBufferPointer to see a class that handles this for you.

Resources