Matthew MacFarland
Matthew MacFarland

Reputation: 2729

What is the leading ? is F# type signature?

When I hover certain methods that come from C# libraries in F#, some of the parameters start with a ?. I'm unfamiliar with this syntax. Does this mean nullable?

Here is an example from hovering the SetStatus method on the Activity class where the description parameter is preceded by a ?. enter image description here

Upvotes: 2

Views: 80

Answers (1)

Piotr Rodak
Piotr Rodak

Reputation: 1941

The optional parameters in F# are declared with question marks in the declaration of the function:

https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/parameters-and-arguments#optional-parameters

What is interesting that the optionality expressed this way turns them to actual options of the base type, however there are differences: The options are 'active' only within the scope of the member method, and you have to pass the underlying type variable (or nothing in this case)

type Test() =
    member this.fn (?i : int) = 
        match i with
        | Some x -> -x
        | None -> 0
  
let t = new Test()

let r1 = t.fn()
printfn "%d" r1

let r2 = t.fn(4)
printfn "%d" r2

If you declare your member method as int option, you can't omit the parameter despite identical implementation of the method otherwise:

type Test() =

    member this.fn (i : int option) = 
        match i with
        | Some x -> -x
        | None -> 0
let t = new Test()

let r1 = t.fn()
printfn "%d" r1

let r2 = t.fn(4)
printfn "%d" r2

Here's the output:

/home/jdoodle.fs(9,14): error FS0001: This expression was expected to have type
    'int option'    
but here has type
    'unit'    

/home/jdoodle.fs(12,15): error FS0001: This expression was expected to have type
    'int option'    
but here has type
    'int'    

In order to make it working, you have to pass int option to the method:

let r1 = t.fn(None)
printfn "%d" r1

let r2 = t.fn(Some 4)
printfn "%d" r

Upvotes: 4

Related Questions