Optional variables and set membership in MiniZinc - set

I have a variable, that should only have a value under certain conditions, so it needs to be an optional variable, I suppose. If that condition is met, the optional variable should be restricted to elements of a set.
The problem is, that MiniZinc does not seem to like optional variables and sets.
How can this be rewritten, so that MiniZinc does not complain?
enum TYPES = { TYPE1, TYPE2 };
enum SUBTYPES = { SUBTYPE1, SUBTYPE2, SUBTYPE3, SUBTYPE4 };
var TYPES: mytype;
var opt SUBTYPES: subtype; % if "opt" is removed, it works
constraint mytype=TYPE1 -> subtype in { SUBTYPE1, SUBTYPE3 };

Your model is almost correct, but is missing the handling of the optional part of subtype in your constraint. Because subtype is not guaranteed to exists, we cannot directly say that it has to be in the set {SUBTYPE1, SUBTYPE3}. Instead, we have to (1) force the value of subtype to exist and (2) then ensure that its value is within the given set.
We can force an optional value to exist by using the occurs intrinsic. Its value, on the other hand can be influenced using the deopt intrinsic. The constraint thus becomes:
constraint mytype=TYPE1 -> (occurs(subtype) /\ deopt(subtype) in { SUBTYPE1, SUBTYPE3 });

Related

Operation applied on values of a type

As mentioned in Go specification:
"A type determines a set of values together with operations and methods specific to those values."
To introduce an operation or method to be applied on the values of a type,
Is that operation applied on values (taken from a set) supposed to give the result (or value) from the same set?
For example, in the below code, findName() is not supposed to be a method on type user. Instead findName() should be a helper function.
type user struct {
name string
email string
age int
}
func (u user) findElder(other user) user {
if u.age >= other.age {
return u
}
return other
}
func (u user) findName() string {
return u.name
}
"operations and methods specific to those values" does not mean that they are unique to those values, or that they result in those values.
According to Google, "specific" means "clearly defined or identified." In this quote from the Go spec, the word "specific" is used with regard to the fact that Go is strongly typed, meaning that operations and methods work on the types that they are defined or identified to work on.
For example, the == operator is specified to work on integer types, thus, the == operator is specific to values of int, int32, uint8, etc.
No, I don't think that the operation applied on values (taken from a set) are supposed to give the result (or value), only from the same set. They can be from a different set of values as well. It all depends on the use case, the design of the type and the operation.
So in your case, findName() can very well be a method even though it is returning something not in the set of input values.

What are scalar types in GraphQL

From their docs, it says:
The leaf values of any request and input values to arguments are Scalars (or Enums) and are defined with a name and a series of serialization functions used to ensure validity
but I am unable to comprehend that definition. From the answer to my previous question, I think scalars are associated with enums. Can someone break down in simpler terms what do GraphQL scalar types do and when to use scalar types as opposed to enum types?
Scalars are equivalent to primitive data types in a programming language. In GraphQL, there are five built-in scalar types:
Boolean, true or false
Int, a signed 32‐bit numeric non‐fractional value
Float, a signed double‐precision fractional values
String, a sequence of UTF‐8 characters
ID, a unique identifier
A scalar simply represents a single value and are the basic building blocks of your schema. This is in comparison to object types, which represent a collection of values. An object type has fields, and each field has a type which may be a scalar or an object type itself. If the field's type is an object, that object will have fields that are also scalars or other objects, and so on. In this way we end up with a tree-like structure in both our schema and the queries made against it.
query { # <- The "root" of the tree
movies {
actors {
name # <- A "leaf" on the tree
}
crew {
name # <- Another "leaf"
}
}
}
Enums are similar to scalars, in that an enum represents a single, concrete value. However, each enum type is defined explicitly in the schema (there are no "built-in" enums) and its definition must include a set of values that the enum type can be. For example, we might create an enum like:
enum Animal {
Cat
Dog
Bird
}
A field that returns an Animal will still have a single value, like a scalar, but that value will be either "Cat", "Dog" or "Bird" -- no other values are allowed.
A leaf type is a term that encompasses both scalars and enums. Leaf types represent the leaves or terminating points in our tree-like queries and their responses.
When a field returns an object type (like movies, actors, or crew in the above example), we have to tell GraphQL which of the object type's fields we want to query. This selection of fields is called a selection set and is wrapped by curly brackets. In our example, name is the selection set for the crew field, crew and actors are the selection set for the movies field, and even the movies field is part of the selection set for the query root type.
The important thing to notice here is that leaf types do not have fields, so any field that returns a leaf type will not have a selection set.
For more information, you can check out the official spec.

Defining a variable in Go programming language

I am learning Go language and comes across seeing this type of variable declaration:
i:=1;
But it says that Go has static variables. i,e variables should be defined in some way like this
var i int=1;
So what is the difference between these two methods? In the first one we don't need to indicate the data type. Why is it so?
The first one i := 1 is called short variable declaration. It is a shorthand for regular variable declaration with initializer expressions but no types:
var IdentifierList = ExpressionList
You don't specify the type of i, but i will have a type based on certain rules. Its type will be automatically inferred. In this case it will be of type int because the initializer expression 1 is an untyped integer constant whose default type is int, so when a type is needed (e.g. it is used in a short variable declaration), int type will be deduced.
So Go is statically typed. That means variables will have a static type and values stored in them at runtime will always be of that type. Being statically typed does not mean you have to explicitly specify the static type, it just means variables must have a static type - decided at compile time - which condition is met even if you use short variable declaration and you don't specify it.
Note that you can also omit the type if you declare a variable with the var keyword:
var i = 1
In which case the type will also be deduced from the type of the initializer expression.
Spec: Variable declaration:
If a type is present, each variable is given that type. Otherwise, each variable is given the type of the corresponding initialization value in the assignment. If that value is an untyped constant, it is first converted to its default type; if it is an untyped boolean value, it is first converted to type bool. The predeclared value nil cannot be used to initialize a variable with no explicit type.
Go is designed with ease of use in mind. So new variables are able to get an implicit type of the right side using the := operator. Also the constant 1 for example has an implicit type in go.

How do the different enum variants work in TypeScript?

TypeScript has a bunch of different ways to define an enum:
enum Alpha { X, Y, Z }
const enum Beta { X, Y, Z }
declare enum Gamma { X, Y, Z }
declare const enum Delta { X, Y, Z }
If I try to use a value from Gamma at runtime, I get an error because Gamma is not defined, but that's not the case for Delta or Alpha? What does const or declare mean on the declarations here?
There's also a preserveConstEnums compiler flag -- how does this interact with these?
There are four different aspects to enums in TypeScript you need to be aware of. First, some definitions:
"lookup object"
If you write this enum:
enum Foo { X, Y }
TypeScript will emit the following object:
var Foo;
(function (Foo) {
Foo[Foo["X"] = 0] = "X";
Foo[Foo["Y"] = 1] = "Y";
})(Foo || (Foo = {}));
I'll refer to this as the lookup object. Its purpose is twofold: to serve as a mapping from strings to numbers, e.g. when writing Foo.X or Foo['X'], and to serve as a mapping from numbers to strings. That reverse mapping is useful for debugging or logging purposes -- you will often have the value 0 or 1 and want to get the corresponding string "X" or "Y".
"declare" or "ambient"
In TypeScript, you can "declare" things that the compiler should know about, but not actually emit code for. This is useful when you have libraries like jQuery that define some object (e.g. $) that you want type information about, but don't need any code created by the compiler. The spec and other documentation refers to declarations made this way as being in an "ambient" context; it is important to note that all declarations in a .d.ts file are "ambient" (either requiring an explicit declare modifier or having it implicitly, depending on the declaration type).
"inlining"
For performance and code size reasons, it's often preferable to have a reference to an enum member replaced by its numeric equivalent when compiled:
enum Foo { X = 4 }
var y = Foo.X; // emits "var y = 4";
The spec calls this substitution, I will call it inlining because it sounds cooler. Sometimes you will not want enum members to be inlined, for example because the enum value might change in a future version of the API.
Enums, how do they work?
Let's break this down by each aspect of an enum. Unfortunately, each of these four sections is going to reference terms from all of the others, so you'll probably need to read this whole thing more than once.
computed vs non-computed (constant)
Enum members can either be computed or not. The spec calls non-computed members constant, but I'll call them non-computed to avoid confusion with const.
A computed enum member is one whose value is not known at compile-time. References to computed members cannot be inlined, of course. Conversely, a non-computed enum member is once whose value is known at compile-time. References to non-computed members are always inlined.
Which enum members are computed and which are non-computed? First, all members of a const enum are constant (i.e. non-computed), as the name implies. For a non-const enum, it depends on whether you're looking at an ambient (declare) enum or a non-ambient enum.
A member of a declare enum (i.e. ambient enum) is constant if and only if it has an initializer. Otherwise, it is computed. Note that in a declare enum, only numeric initializers are allowed. Example:
declare enum Foo {
X, // Computed
Y = 2, // Non-computed
Z, // Computed! Not 3! Careful!
Q = 1 + 1 // Error
}
Finally, members of non-declare non-const enums are always considered to be computed. However, their initializing expressions are reduced down to constants if they're computable at compile-time. This means non-const enum members are never inlined (this behavior changed in TypeScript 1.5, see "Changes in TypeScript" at the bottom)
const vs non-const
const
An enum declaration can have the const modifier. If an enum is const, all references to its members inlined.
const enum Foo { A = 4 }
var x = Foo.A; // emitted as "var x = 4;", always
const enums do not produce a lookup object when compiled. For this reason, it is an error to reference Foo in the above code except as part of a member reference. No Foo object will be present at runtime.
non-const
If an enum declaration does not have the const modifier, references to its members are inlined only if the member is non-computed. A non-const, non-declare enum will produce a lookup object.
declare (ambient) vs non-declare
An important preface is that declare in TypeScript has a very specific meaning: This object exists somewhere else. It's for describing existing objects. Using declare to define objects that don't actually exist can have bad consequences; we'll explore those later.
declare
A declare enum will not emit a lookup object. References to its members are inlined if those members are computed (see above on computed vs non-computed).
It's important to note that other forms of reference to a declare enum are allowed, e.g. this code is not a compile error but will fail at runtime:
// Note: Assume no other file has actually created a Foo var at runtime
declare enum Foo { Bar }
var s = 'Bar';
var b = Foo[s]; // Fails
This error falls under the category of "Don't lie to the compiler". If you don't have an object named Foo at runtime, don't write declare enum Foo!
A declare const enum is not different from a const enum, except in the case of --preserveConstEnums (see below).
non-declare
A non-declare enum produces a lookup object if it is not const. Inlining is described above.
--preserveConstEnums flag
This flag has exactly one effect: non-declare const enums will emit a lookup object. Inlining is not affected. This is useful for debugging.
Common Errors
The most common mistake is to use a declare enum when a regular enum or const enum would be more appropriate. A common form is this:
module MyModule {
// Claiming this enum exists with 'declare', but it doesn't...
export declare enum Lies {
Foo = 0,
Bar = 1
}
var x = Lies.Foo; // Depend on inlining
}
module SomeOtherCode {
// x ends up as 'undefined' at runtime
import x = MyModule.Lies;
// Try to use lookup object, which ought to exist
// runtime error, canot read property 0 of undefined
console.log(x[x.Foo]);
}
Remember the golden rule: Never declare things that don't actually exist. Use const enum if you always want inlining, or enum if you want the lookup object.
Changes in TypeScript
Between TypeScript 1.4 and 1.5, there was a change in the behavior (see https://github.com/Microsoft/TypeScript/issues/2183) to make all members of non-declare non-const enums be treated as computed, even if they're explicitly initialized with a literal. This "unsplit the baby", so to speak, making the inlining behavior more predictable and more cleanly separating the concept of const enum from regular enum. Prior to this change, non-computed members of non-const enums were inlined more aggressively.
There are a few things going on here. Let's go case by case.
enum
enum Cheese { Brie, Cheddar }
First, a plain old enum. When compiled to JavaScript, this will emit a lookup table.
The lookup table looks like this:
var Cheese;
(function (Cheese) {
Cheese[Cheese["Brie"] = 0] = "Brie";
Cheese[Cheese["Cheddar"] = 1] = "Cheddar";
})(Cheese || (Cheese = {}));
Then when you have Cheese.Brie in TypeScript, it emits Cheese.Brie in JavaScript which evaluates to 0. Cheese[0] emits Cheese[0] and actually evaluates to "Brie".
const enum
const enum Bread { Rye, Wheat }
No code is actually emitted for this! Its values are inlined. The following emit the value 0 itself in JavaScript:
Bread.Rye
Bread['Rye']
const enums' inlining might be useful for performance reasons.
But what about Bread[0]? This will error out at runtime and your compiler should catch it. There's no lookup table and the compiler doesn't inline here.
Note that in the above case, the --preserveConstEnums flag will cause Bread to emit a lookup table. Its values will still be inlined though.
declare enum
As with other uses of declare, declare emits no code and expects you to have defined the actual code elsewhere. This emits no lookup table:
declare enum Wine { Red, Wine }
Wine.Red emits Wine.Red in JavaScript, but there won't be any Wine lookup table to reference so it's an error unless you've defined it elsewhere.
declare const enum
This emits no lookup table:
declare const enum Fruit { Apple, Pear }
But it does inline! Fruit.Apple emits 0. But again Fruit[0] will error out at runtime because it's not inlined and there's no lookup table.
I've written this up in this playground. I recommend playing there to understand which TypeScript emits which JavaScript.

this code uses the address of type?

the code at https://code.google.com/p/goauth2/source/browse/oauth/oauth.go#99 declares this type:
package oauth
...
type Config struct {...}
...
the suggested use of this is following:
var config = &oauth.Config{...}
I do not understand why this code takes the address of this type and why this is even possible in Go. I am a newbie. I thought that types are for the compiler, no? Please help.
The Go Programming Language Specification
Composite literals
Composite literals construct values for structs, arrays, slices, and
maps and create a new value each time they are evaluated. They consist
of the type of the value followed by a brace-bound list of composite
elements. An element may be a single expression or a key-value pair.
Given the declaration
type Point3D struct { x, y, z float64 }
one may write
origin := Point3D{} // zero value for Point3D
Taking the address of a composite literal generates a pointer to a
unique instance of the literal's value.
var pointer *Point3D = &Point3D{y: 1000}
It's an example of the use of a pointer to a composite literal.
This is taking the address of a new instance of the Config type, not the address of the type itself.

Resources