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
Now as to why you’re getting that particular error. Take a look at the following line
In F# this is not an assignment but a comparison. So this is an expression which produces a bool value but inside the
forloop all expressions must bevoid/unitreturning. Hence you receive an error.Assignment in F# has at least 2 forms that I am aware of.
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