Thomas
Thomas

Reputation: 12107

How to name return types in F#?

With the following function:

let Calc =
    // do something
    if something
        (false, 0)
    else
        (true, some value)

how can I define name the output fields?

in C# I could do:

(bool Success, int Value) Calc()....

so then when I get my result, I can access the Success and Value fields by name; how can I do the same in F#?

Upvotes: 3

Views: 89

Answers (1)

Chester Husk
Chester Husk

Reputation: 1473

you can name the fields of your tuple by binding to them like so

let Calc () =
    // do something
    if something
        (false, 0)
    else
        (true, some value)

let (success, value) = Calc ()

you don't have to give names to the tuple fields in the definition of Calc itself, you can do so at the places that use Calc. If you'd prefer to give the results names, consider creating record type to contain that:


type CalcData = { success: bool; value: int }

let Calc () = 
  if something then { success = false; value = 0 }
  else { success = true, value = 123 }

let {success = success; value = value} = Calc ()

but it looks like your Calc can either return nothing or some result, which is what the Option type was made for:


let calc () = if something then None else Some 123

match calc () with
| None -> // if calc returned no value then do ....
| Some value -> // if calc returned a value then do ...

Upvotes: 8

Related Questions