What is an instance of Option Type at parsing time? - constraint-programming

About option types, the specification of Minizinc (sec. 6.6.3) says:
Overview. Option types defined using the opt type constructor, define types that may or may not be there. They are similar to Maybe types of Haskell implicity adding a new value <> to the type.
[...]
Initialisation. An opt type variable does not need to be initialised at instance-time. An uninitialised opt type variable is
automatically initialised to <>.
I would like to parse and process the following constraint with two opt types:
predicate alternative(var opt int: s0, var int: d0,
array[int] of var opt int: s,
array[int] of var int: d);
However, I am not sure about what should I expect as values for arguments s0 and s when parsing this constraint.
Can I simply ignore the presence of the opt modifier and assume the constraint signature to be equal to the following one?
predicate alternative(var int: s0, var int: d0,
array[int] of var int: s,
array[int] of var int: d);
If not, how should I handle it?

In MiniZinc variable option types are handled as variables that might not exist. Within the compiler these variables are transformed these variables are interpreted and rewritten in such a way that the FlatZinc output only contains actual variables. Usually this means that an boolean variable is added for every variable that is true if-and-only-if the variable "exists".
For the library writers, there is the option to rewrite it in such a way that your solver will be able to handle best. In the standard library alternative is defined as:
predicate alternative(var opt int: s0, var int: d0,
array[int] of var opt int: s,
array[int] of var int: d) =
assert(index_set(s) = index_set(d),
"alternative: index sets of third and fourth argument must be identical",
sum(i in index_set(s))(bool2int(occurs(s[i]))) <= 1 /\
span(s0,d0,s,d)
);
Notice that the occurs intrinsic is used to test if a variable exists. More intrinsics for variable types can be found in the MiniZinc library: http://www.minizinc.org/doc-lib/doc-optiontypes.html. If necessary, you can also use a let-expression to create extra variable and then map the predicate to an solver intrinsic predicate.
Even if there is no better decomposition of the optional type predicate for your solver, it can still be worthwhile to implement the predicate without option types. Because of MiniZinc's overloading, that implementation will be used whenever the predicate is called with arrays of non-option variable types. (Note though that the alternative predicate is specifically meant for "optional tasks" and is unlikely to be called that way).

Related

What is # symbol in ABAP?

I found a piece of code like in the picture, in this case I know more or less what it causes, but generally I don't know the #( ) syntax.
What is the #( ) syntax and where can I find more about it?
DATA: lv_str TYPE string VALUE 'ABCD'.
DATA: dref1 TYPE REF TO data.
DATA: dref2 TYPE REF TO data.
* Old Syntax
GET REFERENCE OF LV_STR INTO dref1.
* New Syntax
dref2 = REF #( LV_STR ).
BREAK-POINT.
The # is a placeholder for the type of the variable.
You could write line 11 as this as well:
dref2 = REF data( lv_str ).
That would do the same thing. The # automatically takes the type of the variable on the left, if you don't specify it.
I've not seen it with TYPE REF TO before this, but it's fairly common as
VALUE #( )
I haven't found any documentation on the REF #( ) version but here is the official SAP documentation for VALUE #( ), it explains what the # does too.
The documentation of the Reference Operator REF states:
The # character for a data type that is determined by the following hierarchy:
If the data type required in an operand position is unique and known completely, the operand type is used.
If the operand type cannot be derived from the context, the data type of dobj is used.
If the data type of dobj is not known statically, the generic type data is used.
And also, I think that the "mother" documentation chapter is Constructor Operators for Constructor Expressions:
If the data type required in an operand position is unique and can be identified completely, the # character can be used instead of an explicit type specification type and the operand type is used.
If the operand type is not unique and is not known completely, if possible, a type inference is performed to determine a data type.
This is described in each constructor expression.
(NEW, VALUE, CONV, CORRESPONDING, CAST, REF, EXACT, REDUCE, FILTER, COND, SWITCH)

Modeling RLC in OpenModelica. Error - Type mismatch,between Complex and Real

EDITED 28-04-2021
I trying to build a RLC-chain in OpenModelica.
When I entering the several functions in "equation", appears an error (see comments)
I declared some of the variables above, but the errors did not disappear
There are RLC-chain
There are formulas
model Lab5
extends Modelica.Icons.Example;
type Voltage=Real(unit="V");
type Current=Real(unit="A");
type Resistance=Real(unit="Ohm");
type Capacitance=Real(unit="F");
type Inductance =Real(unit="H");
parameter Modelica.SIunits.Resistance R=100 "Resistance";
parameter Modelica.SIunits.Inductance L=1 "Inductance";
parameter Modelica.SIunits.Voltage Vb=24 "Total DC Voltage";
parameter Modelica.SIunits.Capacitance C=1e-3 "Capacitance";
Voltage V;
Current i_L;
Current i_R;
Current i_C;
Current icomp;
equation
Z1_f=Modelica.ComplexMath.'sqrt'(Complex(re=-1)*(2*Modelica.Constants.pi*f*L*(1/(2*Modelica.Constants.pi*f*C)));
** //Error:
Type mismatch in equation Z1_f=Modelica.ComplexMath.'sqrt'(Complex.'*'.multiply(Complex(-1.0, 0.0),
Complex.'constructor'.fromReal(L / C, 0.0))) of type Real=record Complex
Real re;
Real im;
end Complex;.**
Z2_f=R;
KPF=Z2_f/(Z1_f+Z2_f);
APF=ModelicaReference.Operators.'abs(KPF)';
FPF=Modelica.ComplexMath.arg(KPF);
V = i_R * R;
C * der(V) = i_C;
L * der(i_L) = Vb - V;
i_L = i_R + i_C;
annotation(
uses(Modelica(version = "3.2.3")));
end Lab5;
I tried to change the syntax and made this code:
Z1_f=Modelica.ComplexMath.'sqrt'(Complex*Complex(re=2*Modelica.Constants.pi*f*L*(1/(2*Modelica.Constants.pi*f*C))));
But now this error:
Operator overloading requires exactly one matching expression, but found 0 expressions:
But if I assign a complex to one complex in a parenthesis to another complex, thereby assigning 1 argument (not 0, as in the previous error), then the error again refers to the incorrectly composed constructor and the conversion from complex to real.
Z1_f=Modelica.ComplexMath.'sqrt'(Complex(Complex(re=(2*Modelica.Constants.pi*f*L*(1/(2*Modelica.Constants.pi*f*C))))));
The are 2 big errors:
Type mismatch for positional argument 1 in Complex(re=Complex.'constructor'.fromReal(L / C, 0.0)). The argument has type:
record Complex
Real re;
Real im;
end Complex;
expected type:
Real
Complex.'constructor'.fromReal(re=Complex.'constructor'.fromReal(L / C, 0.0)). The argument has type:
record Complex
Real re;
Real im;
end Complex;
expected type:
Real
How I can to solve this problem between the complex and real variablesO?
Because in Modelica a lot of equations between complex and real datas.
This seems like homework, so I will give you some hints.
Instead of defining pi, use Modelica.Constants.pi.
ModelicaReference is just a library for documentation you cannot use any of the (quoted) operators from there, remove ModelicaReference.Operators. and the quotes
You need to declare all the variables that appear in the equation section, with correct type (Real or Complex), you are now missing a lot of them
ModelicaReference.Operators.'abs(KPF)' -> abs(KPF)
as far as I see you are using complex numbers, for that you need to use type Complex
For operators on Complex you use: Complex operators and Modelica.ComplexMath, i.e. Modelica.ComplexMath.'sqrt'(Complex(re=-1, im=0))

How does Haskell know whether a data type declaration is a variable or a named type?

Take a data type declaration like
data myType = Null | Container TypeA v
As I understand it, Haskell would read this as myType coming in two different flavors. One of them is Null which Haskell interprets just as some name of a ... I guess you'd call it an instance of the type? Or a subtype? Factor? Level? Anyway, if we changed Null to Nubb it would behave in basically the same way--Haskell doesn't really know anything about null values.
The other flavor is Container and I would expect Haskell to read this as saying that the Container flavor takes two fields, TypeA and v. I expect this is because, when making this type definition, the first word is always read as the name of the flavor and everything that follows is another field.
My question (besides: did I get any of that wrong?) is, how does Haskell know that TypeA is a specific named type rather than an un-typed variable? Am I wrong to assume that it reads v as an un-typed variable, and if that's right, is it because of the lower-case initial letter?
By un-typed I mean how the types appear in the following type-declaration for a function:
func :: a -> a
func a = a
First of all, terminology: "flavors" are called "cases" or "constructors". Your type has two cases - Null and Container.
Second, what you call "untyped" is not really "untyped". That's not the right way to think about it. The a in declaration func :: a -> a does not mean "untyped" the same way variables are "untyped" in JavaScript or Python (though even that is not really true), but rather "whoever calls this function chooses the type". So if I call func "abc", then I have chosen a to be String, and now the compiler knows that the result of this call must also be String, since that's what the func's signature says - "I take any type you choose, and I return the same type". The proper term for this is "generic".
The difference between "untyped" and "generic" is that "untyped" is free-for-all, the type will only be known at runtime, no guarantees whatsoever; whereas generic types, even though not precisely known yet, still have some sort of relationship between them. For example, your func says that it returns the same type it takes, and not something random. Or for another example:
mkList :: a -> [a]
mkList a = [a]
This function says "I take some type that you choose, and I will return a list of that same type - never a list of something else".
Finally, your myType declaration is actually illegal. In Haskell, concrete types have to be Capitalized, while values and type variables are javaCase. So first, you have to change the name of the type to satisfy this:
data MyType = Null | Container TypeA v
If you try to compile this now, you'll still get an error saying that "Type variable v is unknown". See, Haskell has decided that v must be a type variable, and not a concrete type, because it's lower case. That simple.
If you want to use a type variable, you have to declare it somewhere. In function declaration, type variables can just sort of "appear" out of nowhere, and the compiler will consider them "declared". But in a type declaration you have to declare your type variables explicitly, e.g.:
data MyType v = Null | Container TypeA v
This requirement exist to avoid confusion and ambiguity in cases where you have several type variables, or when type variables come from another context, such as a type class instance.
Declared this way, you'll have to specify something in place of v every time you use MyType, for example:
n :: MyType Int
n = Null
mkStringContainer :: TypeA -> String -> MyType String
mkStringContainer ta s = Container ta s
-- Or make the function generic
mkContainer :: TypeA -> a -> MyType a
mkContainer ta a = Container ta a
Haskell uses a critically important distinction between variables and constructors. Variables begin with a lower-case letter; constructors begin with an upper-case letter1.
So data myType = Null | Container TypeA v is actually incorrect; the first symbol after the data keyword is the name of the new type constructor you're introducing, so it must start with a capital letter.
Assuming you've fixed that to data MyType = Null | Container TypeA v, then each of the alternatives separated by | is required to consist of a data constructor name (here you've chosen Null and Container) followed by a type expression for each of the fields of that constructor.
The Null constructor has no fields. The Container constructor has two fields:
TypeA, which starts with a capital letter so it must be a type constructor; therefore the field is of that concrete type.
v, which starts with a lowercase letter and is therefore a type variable. Normally this variable would be defined as a type parameter on the MyType type being defined, like data MyType v = Null | Container TypeA v. You cannot normally use free variables, so this was another error in your original example.2
Your data declaration showed how the distinction between constructors and variables matters at the type level. This distinction between variables and constructors is also present at the value level. It's how the compiler can tell (when you're writing pattern matches) which terms are patterns it should be checking the data against, and which terms are variables that should be bound to whatever the data contains. For example:
lookAtMaybe :: Show a => Maybe a -> String
lookAtMaybe Nothing = "Nothing to see here"
lookAtMaybe (Just x) = "I found: " ++ show x
If Haskell didn't have the first-letter rule, then there would be two possible interpretations of the first clause of the function:
Nothing could be a reference to the externally-defined Nothing constructor, saying I want this function rule to apply when the argument matches that constructor. This is the interpretation the first-letter rule mandates.
Nothing could be a definition of an (unused) variable, representing the function's argument. This would be the equivalent of lookAtMaybe x = "Nothing to see here"
Both of those interpretations are valid Haskell code producing different behaviour (try changing the capital N to a lower case n and see what the function does). So Haskell needs a rule to choose between them. The designers chose the first-letter rule as a way of simply disambiguating constructors from variables (that is simple to both the compiler and to human readers) without requiring any additional syntactic noise.
1 The rule about the case of the first letter applies to alphanumeric names, which can only consist of letters, numbers, and underscores. Haskell also has symbolic names, which consists only of symbol characters like +, *, :, etc. For these, the rule is that names beginning with the : character are constructors, while names beginning with another character are variables. This is how the list constructor : is distinguished from a function name like +.
2 With the ExistentialQuantification extension turned on it is possible to write data MyType = Null | forall v. Container TypeA v, so that the the constructor has a field with a variable type and the variable does not appear as a parameter to the overall type. I'm not going to explain how this works here; it's generally considered an advanced feature, and isn't part of standard Haskell code (which is why it requires an extension)

what is nim type definition for generic procedure?

I have a strategies expressed as generics in nim:
proc fooStrategy[T](t: T, ...)
proc barStrategy[T](t: T, ...)
I would like to create a lookup table for the strategies by name... so I tried:
type
Strategy*[T] = proc[T](t: T, ...)
let strategies* = toTable[string, Strategy[T]]([
("foo", fooStrategy), ("bar", barStrategy)])
This doesn't work -- the type declaration fails. If I were to get by that I could guess that the table of strategies would also have problems. Is there another way to do this? "T" is supposed to be "some 1D collection type" -- could be sequence, array, vector from blas, etc. I could add concrete strategies to the table for common collections, but I still have the problem with the function pointer, as
type
Strategy* = proc(t: any, ...)
let strategies* = toTable[string, Strategy]([
("foo-seq[int]", fooStrategy[int]), ...])
still has problems. Any suggestions?
There are multiple issues with your code:
Firstly, initTable does not take a list of items for the table. It only takes an initial size. You want to use toTable instead.
Secondly, you must explicitly set a value for the generic parameter T when creating a table, because at runtime, all generic parameters must be bound to a type.
Thirdly, the proc types have to exactly match, including pragmas on the proc. This one's tricky.
Here is a working example:
import tables
type
Strategy*[T] = proc(t: T) {.gcsafe, locks: 0.}
proc fooStrategy[T](t: T) = echo "foo"
proc barStrategy[T](t: T) = echo "bar"
let strategies* = toTable[string, Strategy[int]]([
("foo", fooStrategy[int]), ("bar", barStrategy[int])
])
For this example, I create a table with Strategy[int] values (you cannot have a table with Strategy[T] values as this is not a concrete type). I instantiate both fooStrategy and barStrategy with [int] to match the table type. I added {.gcsafe, locks: 0.} to the type definition. If this is omitted, you will get a compiler error:
test.nim(9, 49) Error: type mismatch: got (Array constructor[0..1, (string, proc (t: int){.gcsafe, locks: 0.})])
but expected one of:
proc (pairs: openarray[(string, Strategy[system.int])]): Table[system.string, Strategy[system.int]]{.gcsafe, locks: 0.}
As you see, the compiler tells you in the first line what it sees and in the third line what it expects. it sees procs with {.gcsafe, locks: 0.} because those pragmas are implicitly assigned to the procs defined above. The pragmas change the type, so to be able to assign those procs to Strategy[T], you have to define the same pragmas to Strategy[T].

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