Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name parameters of F# function declaration

Tags:

f#

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
like image 672
Dax Fohl Avatar asked Sep 16 '25 00:09

Dax Fohl


2 Answers

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 }
like image 89
lobsterism Avatar answered Sep 19 '25 03:09

lobsterism


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"
like image 24
William Barbosa Avatar answered Sep 19 '25 02:09

William Barbosa