Convert C # code to F # (if instruction)

I would like to know how to convert this code line by line from C # to F #. I do not want to use any F # idioms or something like that. I'm trying to figure out how to map C # constructs directly 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 attempt to F #:

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 it does not work. The problem seems to be related to the line minVal = col.Item(i):

This expression was expected to have type     unit     but here has type     bool

What is the problem, really?

+5
source share
5 answers

If you want to convert it line by line, 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 about why you get this particular error. Take a look at the next line

minVal = col.Item(i)

F # , . , , bool, for void/unit. , .

F # 2 , .

// Assigning to a mutable value
let mutable v1 = 42
v1 <- 13

// Assigning to a ref cell
let v1 = ref 0
v1 := 42

, , .

+14

. , , : , . : System.Collections.Generic.List<T> F # 't list. BCL - , , ; F # , n- O (n). , .

, F #, #. 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

, ( , comparable F # ). , , , Seq.reduce, , , , .

let getMin s = Seq.reduce min s

, , Seq.min, .

+6

: = () F #.

: col?

: . : -)

+5

# F #? ( : )

, , " # F #", , :)

+4

:

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
+3

All Articles