DEV Community

Rob Mulpeter
Rob Mulpeter

Posted on

Creating Different Default Value Sets for an F# Record Type

The purpose of this post is to provide you with a simple working example of creating different default value sets assigned to a particular record type in F#. It then demonstrates how to update selected fields when binding that default to a new variable using the with keyword.

The benefit of this approach is that the record type remains immutable. Record types do not support the DefaultValueAttribute so it would mean not needing to go out of your way to create a class with mutable explicit fields.

Below is an example of a Meal record type with two different value bindings, one named defaultBreakfastMeal and the other defaultDinnerMeal. There is nothing syntactically different between a regular binding of a record type and one we choose to use as a default.

Record Type & Default Sets

type Meal = { 
      Food: string
      Drink: string }

let defaultBreakfastMeal: Meal = {
      Food = "Pastry"
      Drink = "Coffee" }

let defaultDinnerMeal: Meal = {
      Food = "Shepherd's Pie"
      Drink = "Water" }
Enter fullscreen mode Exit fullscreen mode

We can later set a new binding but update the returning default values with selected overrides. In this case, the Food value.

let HangoverMeal = {
    defaultBreakfastMeal
    with
        Food = "Irish Breakfast"
}
Enter fullscreen mode Exit fullscreen mode

Output

HangoverMeal.Food = "Irish Breakfast"
HangoverMeal.Drink = "Coffee"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)