Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to specify named arguments for a function in an F# constructor?

Tags:

f#

Is there a way to name the function arguments in a constructor?

type UnnamedInCtor(foo: string -> string -> bool) = 
    member this.Foo: string -> string -> bool = foo
    member this.Bar: a:string -> b:string -> bool = foo
    member this.Fizz = foo

//Does not compile
type NamedInCtor(foo: a:string -> b:string -> bool) = 
    member this.Foo: string -> string -> bool = foo
    member this.Bar: a:string -> b:string -> bool = foo
    member this.Fizz = foo
like image 805
Kenneth Ito Avatar asked Oct 31 '22 07:10

Kenneth Ito


2 Answers

I think that it's impossible in F#, however you can use type abbreviations if you want to document what foo represents:

// Compiles
type aToBToC = string -> string -> bool
type NamedInCtor(foo: aToBToC) = 
    member this.Foo: string -> string -> bool = foo
    member this.Bar: a:string -> b:string -> bool = foo
    member this.Fizz = foo
like image 86
Tomasz Maczyński Avatar answered Jan 04 '23 15:01

Tomasz Maczyński


You would need to de-curry the function in your constructor:

type NamedInCtor(a, b) = 
    member this.Foo: string -> string -> bool = a b
    member this.Bar: string -> string -> bool = a b
    member this.Fizz = a b

Note that a and b are implicitly typed here. You should trust the compiler to do this as much as possible, because it makes your code much more readable.

Remember, functions are first class types and traditional objects are discouraged. What you're asking is essentially "can I name and access some arbitrary subset of this type?" The answer to that is no. If you want that behavior, then you must structure your functions to request it.

like image 45
Esoteric Screen Name Avatar answered Jan 04 '23 15:01

Esoteric Screen Name