Microsoft Solver Foundation Modulo Operator - c#

I'm trying to add a basic constraint to my solver foundation by doing the following:
model.AddConstraint("c1", x % y == 0);
I get a compile error saying "Operator '%' cannot be applied to operands of type 'Microsoft.SolverFoundation.Services.Decision' and 'Microsoft.SolverFoundation.Services.Decision'".
This makes sense since a lot of operators aren't supported. However, a lot of the operators that aren't supported (sin, cos, tan, etc.) are available as specific methods on the Model class such as below:
model.AddConstraint("c1", Model.Sum(x,y) == 0);
If I replace "Sum" with "Mod", there is no method available.
Any ideas on how to perform a modulo operation in Solver Foundation? According to the documentation here, it is supported.
I am going to start using reflector to dig through the code, but I figured I would post it on here also. If I find a solution, I will update my question to include the answer.

Really interesting, I wanted to write the exact same question at SO :-)
I found out that a Mod operator is defined for the OML language at http://msdn.microsoft.com/en-us/library/ff818505(v=vs.93).aspx.
There is an overload of the AddConstraint method, that accepts an expression string(I guess an OML expression?) instead of the Term. Unfortunately, I don't know the right formatting, but once we get the knack out of it, we would be able to use all of the other operators as well.
EDIT
It looks like not every OML expression described in API is working. For example,
SolverContext sc = SolverContext.GetContext();
Model m = sc.CreateModel();
m.AddDecision(new Decision(Domain.IntegerRange(0,10), "a"));
m.AddDecision(new Decision(Domain.IntegerRange(0, 10), "b"));
m.AddConstraint(null, "a > 0");
m.AddConstraint(null, "b == Plus[a,2]");
The Plus[x,y] in this case is working and the solver computes the following decision
a: 1,
b: 3
But if I replace the last constraint with this one
m.AddConstraint(null, "b == Mod[a,2]");
I get an OmlParseException ("Failed to parse OML model. Expression: Mod[a,2]."). I guess we are on our own here and purhaps the best thing we can do is sticking with the answer of user141603.

I don't see Mod at http://msdn.microsoft.com/en-us/library/ff525341(v=vs.93).aspx, but here's a workaround:
Model.Floor(Model.Quotient(x,y))==Model.Ceiling(Model.Quotient(x,y))
This is only true if x/y is an integer, and so x%y==0.
There are also other ways of combining the allowed operators to check if it is divisible. My favorite (though I wouldn't recommend it because of floating point precision) is
Model.Sin(Math.PI*Model.Quotient(x,y))==0

Related

Is there another "is" operator in C#? [duplicate]

This question already has answers here:
Why does is operator behave like == operator?
(3 answers)
Using "is" keyword with "null" keyword c# 7.0
(2 answers)
Closed 2 years ago.
I was teaching my students how to write a function. I used a simple algorithm to determine if a char value is an actual letter (and not a digit or something else).
So I actually typed what my student said (playing dumb on purpose): "if (letter is 'A') {...}"
To my surprise this didn't cause a compiler error. I added the same check for 'B' and 'C' and my program can now determine that A, B and C are indeed letters.
Why does that work? And WHAT exactly am I comparing here?
I'm not actively using type comparisons, which is what the internet keeps turning up.
I did an additional experiment with other values:
char l = 'A';
if (l is 'A')
{
Console.WriteLine("l 'A'...");
}
if (l is "A")
{
// Doesn't compile.
}
int x = 15;
if (x is 15)
{
Console.WriteLine("X is 15.");
}
if (x is 5.6)
{
// Also doesn't compile.
}
As far as I can tell "is" functions as an extended version of the equality (==) operator that also enforces the same type. But I can't find any documentation on it.
is might have two meanings, depending on which version of C# you have.
In older C# versions, is was short for "is assignable to" or "is assignable from", depending on how you read the code in your head. It wouldn't work for the code in your class because it expects a type on the right-hand side, but I include it here for completeness. It's also useful as an efficient and portable null check, ie variable is object is a better way to write variable != null1.
In newer C# versions, is can also be used for pattern matching. This was introduced in C# 72 and extended in C# 8, with more coming in 9. Specifically, the code in the question creates a Constant Pattern expression.
Here's another fun way to see this work. Coming in C# 9, instead of writing a check like this:
if (!string.IsNullOrEmpty(mystring))
You could instead write3
if (mystring is {Length:>0})
Which is nice because it's shorter and you could make an argument removing the negation makes it easier to understand.4
At least, according to one of the developers on the C# team at Microsoft. But what would he know? He only built the thing.
Really, C# 6 if you count exception filters.
Jared Parsons again.
I'd reject that argument on the grounds any gains in removing the negation are less than the subtlety introduced in how we validate for null. But you could try the argument ;) And before anyone asks, I have no idea at this time how the two options perform.

Convert Expression from a Textbox to Math Expression in Code Behind [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
I need a fast runtime expression parser
How do I make it that when someone types in x*y^z in a textbox on my page to calculate that equation in the code behind and get the result?
.NET does not have a built-in function for evaluating arbitrary strings. However, an open source .NET library named NCalc does.
NCalc is a mathematical expressions evaluator in .NET. NCalc can parse
any expression and evaluate the result, including static or dynamic
parameters and custom functions.
Answer from operators as strings by user https://stackoverflow.com/users/1670022/matt-crouch, using built-in .NET functionality:
"If all you need is simple arithmetic, do this.
DataTable temp = new DataTable();
Console.WriteLine(temp.Compute("15 / 3",string.Empty));
EDIT: a little more information. Check out the MSDN documentation for the Expression property of the System.Data.DataColumn class. The stuff on "Expression Syntax" outlines a list of commands you can use in addition to the arithmetic operators. (ex. IIF, LEN, etc.)."
EDIT 2: For convenience, you can put this into a little function like:
public string Eval(string expr)
{
var temp = new System.Data.DataTable();
string result = null;
try
{
result = $"{temp.Compute(expr, string.Empty)}";
}
catch (System.Data.EvaluateException ex)
{
if (ex.Message.ToLower().Contains("cannot find column"))
throw new System.Data.SyntaxErrorException($"Syntax error: Invalid expression: '{expr}'."
+ " Variables as operands are not supported.");
else
throw;
}
return result;
}
So you can use it like:
Console.WriteLine(Eval("15 * (3 + 5) / (7 - 2)"));
giving the expected output:
24
Note that the error handler helps to handle exceptions caused by using variables which are not allowed here. Example: Eval("a") - Instead of returning "Cannot find column [a]", which doesn't make much sense in this context (we're not using it in a database context) it is returning "Syntax error: Invalid expression: 'a'. Variables as operands are not supported."
Run it on DotNetFiddle
There are two main approaches to this problem, each with some variations, as illustrated in the variety of answers.
Option A: Find an existing mathematical expresssion evaluator
Option B: Write your own parser and the logic to compute the result
Before going into some details about this, it is appropriate to stress that interpreting arbitrary mathematical expressions is not a trivial task, for any expression grammar other than "toy" grammars such as these that only accept one or two arithmetic operations and do not allow parenthesis etc.
Understanding that such task is deceivingly trivial, and acknowledging that, after all, interpreting arithmetic expressions of average complexity is a relatively recurrent need for various applications [hence one for which mature solutions should be available], it is probably wise to try and make do with "Option A".
I'd therefore second Jed's recommendation of a ready-make expression evaluator such as NCalc.
It may be useful however to take the time and understand the various concepts and methods associated with parsing and interpreting arithmetic expressions, as if one were going to whip-up one's own implementation.
The key concept is that of a formal grammar. The arithmetic expressions which the evaluator will accept must follow a set of rules such as the list of arithmetic operations allowed. For example will the evaluator support, say, trigonometric functions, or if it does, will this also include say atan2(). The rules also indicate what consitutes an operand, for example will it be allowed to input numerical values as big as say 45 digits. etc. The point is that all these rules are formalized in a grammar.
Typically a grammar works on tokens which have previously been extracted from the raw input text. Essentially at some time in the process, some logic needs to analyze the input string, character by character, and determine which sequences of characters go together. For example in the 123 + 45 / 9.3 expression, the tokens are the integer value 123, the plus operator, the integer value 45, the division operator and finally the 9.3 real value. The task of identifying the tokens and associating them with a token type is the job a lexer. Lexers can be build themselves on a grammar (a grammar which "tokens" are single characters, as opposed to the grammar for the arithmetic expression parser which tokens are short strings produced by the lexer.)
BTW, grammars are used to define many other things beyond arithmetic expressions. Computer languages follow [rather sophiticated] grammars, but it is relatively common to introduce Domain Specific Languages aka DSLs in support of various features of computer applications.
For very simple grammars, one may be able to write the corresponding lexer and parser from scratch. But sooner than later the grammars may get complicated to the point that hand-writing these modules becomes fastidious, bug-prone and maybe more importantly difficult to read. Hence the existence of Lexer and Parser Generators which are stand-alone programs that produce the code of lexers and parsers (in a particular programming language such as C, Java or C#) from a list of rules (expressed in a syntax particular to the generator, though many generators tend to use similar syntaxes, loosely base on BNF).
When using such a lexer/parser generator, work in done in multiple steps:
- first one writes a definition of the grammar (in the generator-specific language/syntax)
- one runs this grammar through the generator.
- one often repeats the above two steps multiple times, because writing a grammar is an exacting exercise: the generator will complain of many possible ambiguities one may write into the grammar.
- eventually the generator produces a source file (in the desired target language such as C# etc.)
- this source is included in the overall project
- other source files in the project may invoke the functions exposed in the source files produced by the generator and/or some logic corresponding to various patterns identified during parsing may readily be may imbedded in the generator produced code.
- the project can then be build as usual, i.e. as if the parser and lexer had be hand-written.
And that's about it for a 20,000 feet high presentation of the process of working with formal grammars and code generators.
A list of parser-generators (aka compiler-compilers) can be found at this link. For simple work in C# I also want to mention Irony. It may be very insightful to peruse these sites, to get a better feel for these concept, even without the intent of becoming a practitioner at this time.
As said, I wish to stress that for this particular application, a ready-made arithmetic evaluator is likely the better approach. The main downside of these would be
some limitations as to what the allowed expression syntax is (either the grammar allowed is too restrictive: you also need say stddev() or is too broad: you don't want your users to use trig functions. With the more mature evaluators, there will be some form of configuration/extension feature which allows dealing with this problem.
the learning curve of such a 3rd party module. Hopefully many of them should be relatively "plug-and-play".
solved with this library http://www.codeproject.com/Articles/21137/Inside-the-Mathematical-Expressions-Evaluator
my final code
Calculator Cal = new Calculator();
txt_LambdaNoot.Text = (Cal.Evaluate(txt_C.Text) / fo).ToString();
now when some one type 3*10^11 he will get 300000000000
You will need to implement (or find a third-party source) an expression parser. This is not a trivial thing to do.
What you need - if you want to do it yourself - is a Scanner (also known as Lexer) + Parser in the code behind which interprets the expression. Alternatively, you can find a 3rd party library which does the job and works similar as the JavaScript eval(string) function does.
Please take a look here, it describes an recursive descent parser. The example is written in C, but you should be able to adapt it to C# easily once you got the idea described in the article.
It is less complicated than it sounds, especially if you have a limited amount of operators to support.
The advantage is that you keep full control on what expressions will be executed (to prevent malicious code injections by the end-user of your website).

Dynamically evaluating statement with multiple equality operators

I've seen quite a few expression parsers / tokenizers that can take a certain string and evaluate the result. For example, you could pump the string:
4+4
into the following code:
MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
//' You always need to initialize a language engine
sc.Language = "VBScript";
//' this is the expression - in a real program it will probably be
//' read from a textbox control
string expr = "4+4";
double res = sc.Eval(expr);
and get 8. But, is there a parsing tool out there that can evaluate the string:
4 = 4 = 4
? So far, all examples fail with an error of not being able to compare a double and boolean (which makes sense from a compilers perspective, but from a human perspective, we can see that this is true). Anyone come across something that can achieve this?
From a human perspective, this is only true if we think of x = y = z as a special operator (with three operands), where it implies x = y, y = z, x = z. That is a specific syntactical interpretation of the expression. A human (particularly a programmer) could also interpret it the same way most compilers do, which is to choose the left-most grouping ( x = y ) and then compare the result of that comparison (a boolean value) to z. Even to a human, this doesn't make sense under this syntax. It only seems obvious from a human perspective because humans are notoriously fuzzy when it comes to choosing a syntax that 'makes sense' for a given context.
If you really want that level of 'fuzziness', you'll need to look into something like Wolfram Alpha, which performs contextual analysis to try to find a best guess for the meaning of the expression. If you enter '4 = 4 = 4' there, it will reply True.
You need to define syntax for your "language" and build parser as your expected behavior is not covered by normal expression syntax (and also normal languages should evaluate it to "false" as every language I heard of implements = as binary operation and hence will endup with "4 = true" at some point). There are tools to build parser for C#...
Side note: to match "a human perspective" is insanely hard problem still not solved even for human to human communication :).
try with
var result = (int) HtmlPage.Window.Eval("4 + 4");

Is there any plugin for VS or program to show type and value etc... of a C# code selection?

What I want to do is be told the type, value (if there is one at compile-time) and other information (I do not know what I need now) of a selection of an expression.
For example, if I have an expression like
int i = unchecked((short)0xFF);
selecting 0xFF will give me (Int32, 255), while selecting ((short)0xFF) will give me (Int16, 255), and selecting i will give me (Int32, 255).
Reason why I want such a feature is to be able to verify my assumptions. It's pretty easy to assume that 0xFF is a byte but it is actually an int. I could of course refer to the C# Language Specifications all the time, but I think it's inefficient to have to refer to it everytime I want to check something out. I could also use something like ANTLR but the learning curve is high.
I do intend to read the entire specs and learn ANTLR and about compilers, but that's for later. Right now I wish to have tools to help me get the job done quickly and accurately.
Another case in point:
int? i = 0x10;
int? j = null;
int x;
x = (i >> 4) ?? -1;//x=1
x = (j >> 4) ?? -1;//x=-1
It may seem easy to you or even natural for the bottom two lines in the code above. (Maybe one should avoid code like these, but that's another story) However, what msdn says about the null-coalescing operator is lacking information to tell me that the above code ((i>>4)??) is legal (yet it is, and it is). I had to dig into grammar in the specs to know what's happening:
null-coalescing-expression
conditional-or-expression
conditional-and-expression
exclusive-or-expression
and-expression
equality-expression
relational-expression
shift-expression
shift-expression right-shift additive-expression
... (and more)
Only after reading so much can I get a satisfactory confirmation that it is valid code and does what I think it does. There should be a much simpler way for the average programmer to verify (not about validity, but whether it behaves as thought or not, and also to satisfy my curiosity) such code without having to dive into that canonical manual. It doesn't necessary have to be a VS plugin. Any alternative that is intuitive to use will do just as well.
Well, I'm not aware of any add-ins that do what you describe - however, there is a trick you can use figure out the type of an expression (but not the compile-time value):
Assign the expression to a var variable, and hover your mouse over the keyword var.
So for example, when you write:
var i = unchecked((short)0xFF);
and then hover your mouse over the keyword var, you get a tooltip that says something like:
Struct System.Int16
Represents a 16-bit signed integer.
This is definitely a bit awkward - since you have to potentially change code to make it work. But in a pinch, it let's you get the compiler to figure out the type of an expression for you.
Keep in mind, this approach doesn't really help you once you start throwing casts into the picture. For instance:
object a = 0xFF;
var z = (string)a; // compiles but fails at runtime!
In the example above, the IDE will dutifully report that the type of var z is System.String - but this is, of course, entirely wrong.
Your question is a little vague on what you are looking for, so I don't know if "improved" intellisense solves it, but I would try the Productivity Power Tools.

How do I pronounce "=>" as used in lambda expressions in .Net [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Closed 2 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I very rarely meet any other programmers!
My thought when I first saw the token was "implies that" since that's what it would read it as in a mathematical proof but that clearly isn't its sense.
So how do I say or read "=>" as in:-
IEnumerable<Person> Adults = people.Where(p => p.Age > 16)
Or is there even an agreed way of saying it?
I usually say 'such that' when reading that operator.
In your example, p => p.Age > 16 reads as "P, such that p.Age is greater than 16."
In fact, I asked this very question on the official linq pre-release forums, and Anders Hejlsberg responded by saying
I usually read the => operator as "becomes" or "for which". For example,
Func f = x => x * 2;
Func test = c => c.City == "London";
reads as "x becomes x * 2" and "c for which c.City equals London"
As far as 'goes to' - that's never made sense to me. 'p' isn't going anywhere.
In the case of reading code to someone, say, over the phone, then as long as they're a fellow C# programmer, I'd just use the word 'lambda' - that is, "p lambda p dot age greater-than sixteen."
In comments Steve Jessop mentioned 'maps to' in the case of transformations - so taking Anders' example:
x => x * 2;
would read
x maps to x times 2.
That does seem much closer to the actual intention of the code than 'becomes' for this case.
From MSDN:
All lambda expressions use the lambda
operator =>, which is read as "goes
to".
Reading Code Over the Telephone
From Eric Lippert:
I personally would say c=>c+1 as "see goes to see plus one". Some variations that I've heard:
For a projection, (Customer c)=>c.Name: "customer see becomes see dot name"
For a predicate, (Customer c)=>c.Age > 21: "customer see such that see dot age is greater than twenty-one"
I've always called it the "wang operator" :-)
"p wang age of p greater than 16"
I've seen people say, "Arrow."
I use "goes to" because a LINQ book told me to :)
How about "maps to"? It's both succinct and arguably more technically accurate (i.e. no suggestion of a state change as with "goes to" or "becomes", no conflation of a set with its characteristic function as with "such that" or "for which") than the other alternatives. Though if there's already a standard as the MSDN page appears to imply, maybe you should just go with that (at least for C# code).
"Maps to" is my preferred pronunciation. Mathematically speaking, a function "maps" its arguments to its return value (one might even call the function a "mapping"), so it makes sense to me to use this terminology in programming, particularly as functional programming (especially the lambda calculus) is very close to mathematics. It's also more neutral than "becomes", "goes to", etc., since it doesn't suggest change of state, as contextfree mentioned.
I haven't thought it about much, but I just succintly say "to". It's short and concise, and implies that the variable is passed to the expression. I suppose it could be confused with the numeral 2 ("two"), but I tend to pronounce "to" more like "ta" when speaking. Nobody (who knows lambdas, at least) has ever told me they thought it ambiguous...
// "Func f equals x to x times two"
Func f = x=> x * 2;
// "Func test equals c to c dot City equals London"
Func test = c => c.City == "London"
My short answer: "c 'lambda-of' e". Although I am clinging to "'lambda' c 'function' e", I think lambda-of is the ecumenical compromise. Analysis follows.
This is a great question if only for the bizarre answers. Most of the translations have other meanings than for lambda expressions, leading to exotic interpretations. As an old lambda-expression hacker, I just ignore the .NET notation and rewrite it as lambda in my head while wishing they had done almost anything else for this.
For narrating code over the phone, you want someone to be able to write the code down in sequence. That is a problem, of course, but lambda-arrow or something is probably the best you can get, or maybe lambda-in, but lambda-of is the most accurate.
The problem is the infix usage and how to name the whole thing and the role of the left and right parts with something that works when spoken in the infix place.
This may be an over-constrained problem!
I wouldn't use "such that" because that implies that the right hand side is a predicate that the left-hand side should satisfy. That is very different from talking about a right-hand side from which the left-hand side has been abstracted as a functional parameter. (The MSDN statement about "All lambda expressions" is simply offensive as well as inaccurate.)
Something rankles about "goes to" although it may be as close as we can get. "Goes to" implies a transformation, but there is not exactly some variable c that goes to an expression in c. The abstraction to a function is a little elusive. I could get accustomed to this, but I still yearn for something that emphasizes the abstraction of the variable.
Since the left-hand side is always a simple identifier in the cases used so far [but wait for extensions that may confuse this later on], I think for "c => expression" I would read "c 'lambda-function' expression"' or even "c 'arg' 'function' expression". In the last case, I could then say things like "b 'arg' c 'arg' 'function' expression".
It might be better to make it even more clear that a lambda-expression is being introduced and say something like "'arg' b 'arg' c 'function' expression".
Figuring out how to translate all of this to other languages is an exercise for the student [;<).
I still worry about "(b, c) => expression" and other variants that may come into being if they haven't already. Perhaps "'args' b, c 'function' expression".
After all of this musing, I notice that I am coming around to translating "c => e" as "'lambda' c 'function' e" and noticing that the mapping to exact form is to be understood by context: λc(e), c => e, f where f(c) = e, etc.
I expect that the "goes-to" explanation will prevail simply because this is where a dominant majority is going to see lambda expressions for the first time. That's a pity. A good compromise might be "c 'lambda-of' e"
If you imagine a lambda expression as the anonymous method that it is, "goes to" makes decent sense enough.
(n => n == String.Empty)
n "goes to" the expression n == String.Empty.
It goes to the anonymous method, so you don't have to go to the method in the code!
Sorry for that.
Honestly, I don't like to use "goes to" in my head, but I saw other people saying it seemed weird, and I thought I'd clear that up.
Apart from acquiring the preceding scope (all variables and constants that are in scope for a normal line of code at the point where a lambda expression occurs are available to the code of the expression) a lambda expression is essentially syntactic sugar for an inline function.
The list of values to the left of the production operator ("=>") contributes the structure and content of the stack frame used to make the call to this function. You could say that the list of values contributes both the parameter declarations and the arguments that are passed; in more conventional code these determine the structure and content of the stack frame used to make the call to a function.
As a result, the values "go to" the expression code. Would you rather say "defines the stack frame for" or "goes to" ? :)
In the narrowly defined application of boolean expressions used as filter conditions (a dominant use of lambda expressions extensively considered by other answers to this question) it is very reasonable to skip the method in favour of the intent of the code, and this leads to "for which" being just as succinct and saying more about the meaning of the code.
However, lambda expressions are not the sole province of Linq and outside of this context the more general form "goes to" should be used.
But why "goes to" ?
Because "populates the stack frame of the following code" is far too long to keep saying it. I suppose you could say "is/are passed to".
A crucial difference between explicitly passed parameters and captured variables (if I remember correctly - correct me if I'm wrong) is that the former are passed by reference and the latter by value.
Part of the problem is that you can read it out loud differently depending on how it's structured. It's a shame it's not as pretty or as integrated as ruby's |'s.
In Ruby, this same sybmol is called "hashrocket," and I've heard C# programmers use that term too (even though doing so is wrong).
My two cents:
s => s.Age > 12 && s.Age < 20
"Lambda Expression with parameter s is { return s.Age > 12 && s.Age < 20; }"
I like this because it reminds me of where lamdba expression comes from
delegate(Student s) { return s.Age > 12 && s.Age < 20; };
=> is just a shortcut so you don't have to use the delegate keyword and include the type info since it can be inferred by the compiler.
My term for => as applied to the examples shown result
'result = s => s.Age > 12 && s.Age < 20'
s where s.Age is greater than 12 and s.Age less than 20
'result = x => x * 2'
x where x is multiplied by 2
'result = c => c.City == "London"'
c where c.city is equivalent to "London"
'result = n => n == String.Empty'
n where n is an empty string

Categories

Resources