Dax Fohl
Dax Fohl

Reputation: 10781

How to name parameters of F# function declaration

If I've got a record type that contains all the database functions like so

type Database =
  { getThingsByCountThenLength: int -> int -> Thing list
    getUsersByFirstNameThenLastName: string -> string -> User list }

Is there any way to name the input parameters, so it's more clear? Something like the following (which doesn't compile)

type Database =
  { getThings: count:int -> length:int -> Thing list
    getUsers: firstName:string -> lastName:string -> User list }

(Note it does work for interfaces; I just want it for records.)

type IDatabase =
  abstract getThings: count:int -> length:int -> Thing list
  abstract getUsers: firstName:string -> lastName:string -> User list

Upvotes: 4

Views: 310

Answers (3)

Tomas Petricek
Tomas Petricek

Reputation: 243096

As already mentioned, I don't think you can name parameters of a function inside a record.

However, you can name parameters of members inside an interface. If you were happy with using an interface, then you could write something like this:

type IDatabase =
  abstract GetThingsByCountThenLength : 
    count:int -> length:int -> Thing list
  abstract GetUsersByFirstNameThenLastName : 
    firstName:string -> lastName:string -> User list

For types that are used across multiple files, I generally prefer to follow the .NET coding style for this and so I would probably choose an interface - unless there are some good reasons for choosing a record. However, this is certainly a matter of personal preference & style.

Upvotes: 3

lobsterism
lobsterism

Reputation: 3509

This is not a direct answer (I don't think there is one), but as an alternative you can use single-case union types, which will not only add clarity and continue to allow currying, but also enforce compile-time correctness.

type Count = Count of int
type Length = Length of int
type FirstName = FirstName of string
type LastName = LastName of string

type Database =
  { getThings: Count -> Length -> Thing list
    getUsers: FirstName -> LastName -> User list }

Upvotes: 5

William Barbosa
William Barbosa

Reputation: 5005

Type aliases might be what you want:

type count = int
type length = int
type firstName = string
type lastName = string

type Database =
  { getThings: count -> length -> Thing list
    getUsers: firstName -> lastName -> User list }

Though, in this case, they look rather weird


Other option is using a record instead

type whatever = {
  count : int;
  length : int;
}

let param = { count = 1; length = 1; }

param |> printfn "%A"

Upvotes: 3

Related Questions