Optional parameters in Fsharp records
I am assuming that you mean "optional" as in "field I do not provide when instantiating". However, there is nothing like an optional field in F # records unfortunately (or fortunately depending on your point of view). All of the specified record fields must be present at the time you instantiate.
See also this related question .
You can consider this tradeoff:
-
Use a recording . Every time you update an entry, the F # compiler will scream and warn you about all the places where you have used this entry, and now you need to provide more information. Additional information may be
None
for the fields you added if they are parameters. The big advantage is that your code doesn't have to handle everything, possibly many of the "what iffield1
missing? What if missingfield2
?" -
Use the class . When you update a class, the F # compiler will not perform any completeness checks on the information you put in the class. (You can view records as classes where all fields are constructor arguments and all must be supplied). Hence, there is no overhead to update the class definition, but your code should handle any missing values.
I personally prefer records only because it makes me wonder about the implications of adding a new field.
There is, of course, an average: you can use records, but create them all via static members or something similar:
type Name =
{
First: string
Family: string
}
static member Create(first, family) = { First = first; Family = family}
If in your code you always use Name.Create
to instantiate a record, you can of course add a field MiddleName
without notifying the consumer.
source to share
Option type is preferred over zero in F # for the simple reason that "uninitialized variables" don't exist in the functional way of thinking.
Begin by creating a post VacationRequest
that needs to be approved by the boss.
type VacationRequest =
{Name : string
Date : DateTime
Approval : string option}
The problem with your approach is that all fields must be assigned on build, so this won't compile:
let holiday =
{Name = "Funk"
Date = DateTime(2020,12,31)}
You can work around this by using a helper function that implicitly sets the parameter value.
let fillInRequest name date =
{Name = name
Date = date
Approval = None}
Now you can create a post using the helper function.
let holiday = fillInRequest "Funk" <| DateTime(2020,12,31)
Something funny was noticed when submitting the code to FSI.
val holiday : VacationRequest = {Name = "Funk";
Date = 31/12/2020 12:00:00 ;
Approval = null;}
The boss can then update the request (by creating a new entry )
let approvedHoliday =
{holiday with Approval = Some "boss' name"}
val approvedHoliday : VacationRequest = {Name = "Funk";
Date = 31/12/2020 12:00:00 ;
Approval = Some "boss' name";}
or send it back unchanged
let betterLuckNextTime = holiday
source to share