/home/gimpf/on-topic

F# - Unexpected Tuples

As I am nothing but a dilettante in F#, I still get surprised on the simplest of cases. This week’s glorious “get-it-compiling” issue was about initializing a new instance of a class.

Given a class with a few fields…

type R() =
  member val A = 0 with get, set
  member val B = 0 with get, set

…one might try to conditionally initialize them with some values…

let s = R(A = if 1 < 0 then 0 else 1,
          B = if 0 < 1 then 0 else 1)

…and then get this nice compiler output (which really says it all, but I am not yet up to speed on that either):

  let s = R(A = if 1 < 0 then 0 else 1,
  -----------------------------------^

stdin(41,36): error FS0001: This expression was expected
to have type
    int
but here has type
    'a * 'b

Here it says it: I want an int, I get a tuple. The reason is that the comma operator separates tuple elements, and it seems that in this case the compiler prefers to interpret it as the appending a tuple element to the result of the else-branch, rather than separating the field initializers. After recognizing this:

let s = R( A = if 1 < 0 then 0 else 1
         , B = if 0 < 1 then 0 else 1)