Converting C# code to F# (if statement) - c#

I'd like to know how to convert this code line by line from C# to F#. I am not looking to use any kind of F#'s idioms or something of the like. I am trying to understand how to map directly C#'s constructs to F#.
Here is the C# code:
//requires l.Length > 0
int GetMinimumValue(List<int> l) {
int minVal = l[0];
for (int i = 0; i < l.Length; ++i) {
if (l[i] > minValue) {
minVal = l[i];
}
}
return minVal;
}
And here is my F# attempt:
let getMinValue (l : int list) =
let minVal = l.Head
for i = 0 to (l.Length-1) do
if (l.Item(i) > minVal) then
minVal = col.Item(i)
minVal
Now, this ain't working. The problem seems to be related with the minVal = col.Item(i) line:
This expression was expected to have type unit but here has type bool
What is the problem, really?

If you want to convert it line by line then try the following
let getMinValue (l:System.Collections.Generic.List<int>) =
let mutable min = l.Item(0)
for i = 0 to (l.Count-1) do
if l.Item(i) < min then min <- l.Item(i)
min
Now as to why you're getting that particular error. Take a look at the following line
minVal = col.Item(i)
In F# this is not an assignment but a comparison. So this is an expression which produces a bool value but inside the for loop all expressions must be void/unit returning. Hence you receive an error.
Assignment in F# has at least 2 forms that I am aware of.
// Assigning to a mutable value
let mutable v1 = 42
v1 <- 13
// Assigning to a ref cell
let v1 = ref 0
v1 := 42
And of course, you should absolutely read Brian's article on this subject. It's very detailed and goes over many of the finer points on translating between the two languages
http://lorgonblog.spaces.live.com/Blog/cns!701679AD17B6D310!725.entry

There are a few problems with your literal translation. First of all, there's the immediate problem which causes the compiler error: as others have noted, let bindings are immutable by default. However, there's at least one other big problem: System.Collections.Generic.List<T> is very different from F#'s 't list. The BCL type is a mutable list backed by an array, which provides constant time random access to elements; the F# type is an immutable singly linked list, so accessing the nth element takes O(n) time. If you insist on doing expression-by-expression translation, you may find this blog post by Brian valuable.
I'd strongly recommend that you follow others' advice and try to acclimate yourself to thinking in idiomatic F# rather than literally translating C#. Here are some ways to write some related functions in F#:
// Given an F# list, find the minimum element:
let rec getMinList l =
| [] -> failwith "Can't take the minimum of an empty list"
| [x] -> x
| x::xs ->
let minRest = getMin xs
min x minRest
Note that this works on lists of any element type (with the caveat that the element type needs to be comparable from F#'s perspective or the application of the function will cause a compile-time error). If you want a version which will work on any type of sequence instead of just on lists, you could base it on the Seq.reduce function, which applies the function supplied as its first argument to each pair of elements in a sequence until a single value remains.
let getMin s = Seq.reduce min s
Or best of all, you can use the built-in Seq.min function, which is equivalent.

Short answer: = is not (mutable) assignment in F#.
Question: Do you really mean col?
Suggestions: Try to write this with NO assignments. There is recursion and built-in functions at your disposal :-)

You should read
What does this C# code look like in F#? (part one: expressions and statements)
I am disappointed that none of the other answers already linked it, because people ask the 'how to convert C# to F#' question a lot, and I have posted this answer link a lot, and by now some of the other answerers should know this :)

This is the most literal translation possible:
let getMinimumValue (l: List<int>) =
let mutable minVal = l.[0]
for i=0 to l.Length-1 do
if l.[i] > minVal then
minVal <- l.[i]
minVal

Related

What Does i++ Really Mean?

The question has been asked many times, "What's the difference between i++ and ++i". The accepted answer at What is the difference between i++ and ++i?, and I've seen this language in many other places as well, is that, "i++ means 'tell me the value of i, then increment', whereas ++i means 'increment i, then tell me the value'.
What confuses me is that I was not aware that we were discussing getting back a value for i in either scenario. I thought that i++ is syntactically equivalent to:
i = i + 1;
which is a statement, not an expression, so I don't understand where i is being returned at all.
Can you please expain what the statement actually means?
Thanks,
For reasons unknown to me, this old question with an accepted answer is attracting new answers today, many of which contain significant errors or omissions. Let me attempt to answer the question as asked definitively.
The question has been asked many times, "What's the difference between i++ and ++i". The accepted answer at [...], and I've seen this language in many other places as well, is that, "i++ means 'tell me the value of i, then increment', whereas ++i means 'increment i, then tell me the value'.
As I noted in my answer to that same question: this characterization is common and a reasonable first cut at understanding but unfortunately misleading when you look at the semantics more carefully. Please do not be misled by this vague and not entirely accurate characterization. Read my answer to that question instead.
What confuses me is that I was not aware that we were discussing getting back a value for i in either scenario. I thought that i++ is syntactically equivalent to i = i + 1; which is a statement, not an expression, so I don't understand where i is being returned at all.
You have a number of misunderstandings here. Rather than attack them all, let's just say what the truth is.
First, ++i and i++ are not syntactically exactly equivalent to anything. You cannot necessarily take a legal program that contains an ++i or an i++ and transform it solely syntactically into another legal program. So just banish that thought from your head. These are morally equivalent to increment-and-assign, and ought to be semantically equivalent, but there is not necessarily a syntactic desugaring that preserves program semantics or legality.
Let us now say some more true things. But first, some caveats. For the purposes of this discussion, the incremented expression i is a variable of type int, which can be evaluated either as a variable or a value without side effects, including exceptions. Moreover, we suppose that the incrementing operation does not produce an exception. And moreover we presume a single thread of execution. If you wish to know the semantics of increments and assignments in cases where evaluating the variable can throw, or produce another side effect, or is not a variable but rather is a property, or the operations are user-defined, or multiple threads are observing or mutating the variable, see the specification for details.
That said, here are some true facts:
++i, i++, and i = i + 1 are expressions
++i;, i++; and i = i + 1; are statements
The semantics of ++i are as follows:
temp1 is given the value of i
temp2 is given the value of temp1 + 1
i is given the value of temp2
the value of the expression is temp2
The semantics of i++ are as follows:
temp1 is given the value of i
temp2 is given the value of temp1 + 1
i is given the value of temp2
the value of the expression is temp1
Notice that the difference between the two forms is only what the value produced is. The steps that are taken to produce the side effect are identical in both cases. You are guaranteed in single-threaded C# that the side effect is observed complete before the value is produced.
The semantics of i = i + 1 are as follows:
temp1 is given the value of i
temp2 is given the value of temp1 + 1
i is given the value of temp2
the value of the expression is temp2
Notice that the semantics of i = i + 1 are identical to the semantics of ++i. This is not a guarantee that you can syntactically substitute i = i + 1 for ++i or vice versa, in an arbitrary program. In certain programs, this might be possible.
Notice that the semantics of i++ does not admit an "easy" semantically equivalent form. ((Func<int, int, int>)((int j, int k)=>j))(i, i=i+1) has the same semantics but is obviously a crazy thing to type.
The semantics of the statement forms of all three are:
Evaluate the expression as normal.
Discard the result.
Hopefully this definitively clears up any misunderstandings about what is an expression, what is a statement, what side effects and values are produced by the expressions, and in what order do they happen. Again, note that this explanation is narrowly targeted at simple cases involving integer variables without side effects on a single thread. For the details of how these operations work on other types, or interact with exceptions, or how they work in multithreaded programs, consult the C# specification or ask a more specific question.
Finally: I personally still find all this confusing, and I've been programming in C descendant languages for 30 years and I implemented these semantics in C#. If I find them confusing, and if almost every answer to every question I see on these operators contains significant errors or omissions, then we can safely conclude that these are confusing operators. As a result, I almost never use ++ or -- in my production code. I think it is bad style to have an expression that is useful for both its value and its side effects.
Try to find a way to structure your program so that ever statement has one side effect, and side-effecting expressions are limited to expression statements. Avoid ++, and particularly avoid any scenario where i++ and ++i would have different semantics, because that's a point where the program is going to be harder to understand and therefore harder to maintain correctly.
Edit: See Eric's answer, mine is meh.
You are right. The ++ is equivalent to i = i + 1, but the point to remember is that i = i + 1 is not only a statement, but can also be used as an expression:
Console.WriteLine((i = i + 1) * 42); // will inc i, and then print i*42
Console.WriteLine(++i * 42); // exactly same
Console.WriteLine(i++ * 42); // will inc i, and print old_i*42
Console.WriteLine((i++) * 42); // exactly same
So to conclude simply:
// this
int j = ++i * 42;
// behaves like
int j = (i = i + 1) * 42;
// but this
int j = i++ * 42;
// actually behaves like
int prev = i;
i = i + 1;
int j = prev * 42;
I think you may consider the following two functions to get an analogy to the i++ and ++i.
Fiddle
public static int IPlusPlus(ref int i) {
// simply increment i before returning it
i = i + 1;
return i;
}
public static int PlusPlusI(ref int i) {
// increment i only after you already returned it
try {
return i;
}
finally {
i = i + 1;
}
}
Just like function calls, i++ and ++i are right-hand-side expressions, meaning var a = i++; and var a = ++i; are valid statements. But i++ = 5; and ++i = 5; are not valid as that would use them as left-hand-side expressions.

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");

string(";P") is bigger or string("-_-") is bigger?

I found very confusing when sorting a text file. Different algorithm/application produces different result, for example, on comparing two string str1=";P" and str2="-_-"
Just for your reference here gave the ASCII for each char in those string:
char(';') = 59; char('P') = 80;
char('-') = 45; char('_') = 95;
So I've tried different methods to determine which string is bigger, here is my result:
In Microsoft Office Excel Sorting command:
";P" < "-_-"
C++ std::string::compare(string &str2), i.e. str1.compare(str2)
";P" > "-_-"
C# string.CompareTo(), i.e. str1.CompareTo(str2)
";P" < "-_-"
C# string.CompareOrdinal(), i.e. CompareOrdinal(w1, w2)
";P" > "-_-"
As shown, the result varied! Actually my intuitive result should equal to Method 2 and 4, since the ASCII(';') = 59 which is larger than ASCII('-') = 45 .
So I have no idea why Excel and C# string.CompareTo() gives a opposite answer. Noted that in C# the second comparison function named string.CompareOrdinal(). Does this imply that the default C# string.CompareTo() function is not "Ordinal" ?
Could anyone explain this inconsistency?
And could anyone explain in CultureInfo = {en-US}, why it tells ;P > -_- ? what's the underlying motivation or principle? And I have ever heard about different double multiplication in different cultureInfo. It's rather a cultural shock..!
?
std::string::compare: "the result of a character comparison depends only on its character code". It's simply ordinal.
String.CompareTo: "performs a word (case-sensitive and culture-sensitive) comparison using the current culture". So,this not ordinal, since typical users don't expect things to be sorted like that.
String::CompareOrdinal: Per the name, "performs a case-sensitive comparison using ordinal sort rules".
EDIT: CompareOptions has a hint: "For example, the hyphen ("-") might have a very small weight assigned to it so that "coop" and "co-op" appear next to each other in a sorted list."
Excel 2003 (and earlier) does a sort ignoring hyphens and apostrophes, so your sort really compares ; to _, which gives the result that you have. Here's a Microsoft Support link about it. Pretty sparse, but enough to get the point across.

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.

Vectorising operators in C#

I spend much of my time programming in R or MATLAB. These languages are typically used for manipulating arrays and matrices, and consequently, they have vectorised operators for addition, equality, etc.
For example, in MATLAB, adding two arrays
[1.2 3.4 5.6] + [9.87 6.54 3.21]
returns an array of the same size
ans =
11.07 9.94 8.81
Switching over to C#, we need a loop, and it feels like a lot of code.
double[] a = { 1.2, 3.4, 5.6 };
double[] b = { 9.87, 6.54, 3.21 };
double[] sum = new double[a.Length];
for (int i = 0; i < a.Length; ++i)
{
sum[i] = a[i] + b[i];
}
How should I implement vectorised operators using C#? These should preferably work for all numeric array types (and bool[]). Working for multidimensional arrays is a bonus.
The first idea I had was to overload the operators for System.Double[], etc. directly. This has a number of problems though. Firstly, it could cause confusion and maintainability issues if built-in classes do not bahave as expected. Secondly, I'm not sure if it is even possible to change the behaviour of these built-in classes.
So my next idea was to derive a class from each numerical type and overload the operators there. This creates the hassle of converting from double[] to MyDoubleArray and back, which reduces the benefit of me doing less typing.
Also, I don't really want to have to repeat a load of almost identical functionality for every numeric type. This lead to my next idea of a generic operator class. In fact, someone else had also had this idea: there's a generic operator class in Jon Skeet's MiscUtil library.
This gives you a method-like prefix syntax for operations, e.g.
double sum = Operator<double>.Add(3.5, -2.44); // 1.06
The trouble is, since the array types don't support addition, you can't just do something like
double[] sum = Operator<double[]>.Add(a, b); // Throws InvalidOperationException
I've run out of ideas. Can you think of anything that will work?
Create a Vector class (actually I'd make it a struct) and overload the arithmentic operators for that class... This has probably been done already if you do a google search, there are numerous hits... Here's one that looks promising Vector class...
To handle vectors of arbitrary dimension, I'd:
design the internal array which would persist the individual floats for each of the
vectors dimension values an array list of arbitrary size,
make the Vector constructor take the dimension as an constructor parameter,
In the arithmentic operator overloads, add a validation that the two vectors being added, or subtracted have the same dimension.
You should probably create a Vector class that internally wraps an array and overloads the arithmetic operators. There's a decent matrix/vector code library here.
But if you really need to operate on naked arrays for some reason, you can use LINQ:
var a1 = new double[] { 0, 1, 2, 3 };
var a2 = new double[] { 10, 20, 30, 40 };
var sum = a1.Zip( a2, (x,y) => Operator<double>.Add( x, y ) ).ToArray();
Take a look at CSML. It's a fairly complete matrix library for c#. I've used it for a few things and it works well.
The XNA Framework has the classes you may be able to use. You can use it in your application like any other part of .NET. Just grab the XNA redistributable and code away.
BTW, you don't need to do anything special (like getting the game studio or joining the creator's club) to use it in your application.

Categories

Resources