Adding "abstract" method to a record

Hi folks and happy to have joined.
Now the pleasantries are done, :smile:, a question:
I have created the following record in an attempt to translate a C# class to F#:

type Days = Days of int
type Value = Value of int
type Item = {
    Name: string
    Expires: Days
    Value: Value
}

Thing is I also need every Item to have aā€¦ ā€œwayā€, to run another function, yet not defined, handleDevalue, which acts on the item itself to manipulate the itemā€™s Valueā€¦ ah, value. :slightly_smiling_face:

The handleDevalue function is dependent on the Expires property of the item and thus each itemā€™s implementation of it would be different, with the only common thread being the functionā€™s name and signature (Item -> Item).
On the C# code Iā€™m translating this method was defined as abstract on the Item class and overriden on every item instantiated (where every item is a subclass inheriting from Item).

What Iā€™ve tried, unsuccessfully till now:

  1. Add an abstract method on the record: ...} with abstract handleDevalue: Item -> Item.
    1.1 Reason for failure: IDE tells me ā€œabstract canā€™t be added here as an augmentationā€ (or something close to the same effect). (Iā€™m not F#-savvy enough to even know what it means, but the compiler wonā€™t let it compile soā€¦ no).
  2. Add handleDevalue as a function on the record: {... HandleDevalue: Item -> Item...}.
    2.1. Reason for failure: this function is dependent on the Expires property. Apparently a recordā€™s fields are mutually independent of each other, and besidesā€¦ how will the function ā€œknowā€ which item to act on (itā€™s supposed to act on the item itself)? The this keyword is not allowed when implementing a function when ā€œinstantiatingā€ a record (i.e. no {...handleDevalue = fun this -> <some implementation code here>).
  3. I could remember to define the function on every item I create (I should anyway), but thatā€™s not using the type system to my advantage. I want the compiler to force me to implement the function and remind me if I donā€™t.

With these ways failing Iā€™m out of ideas how to move forward.

Thanks for any advice in advance and sorry if you meet this question on other media, Iā€™m spreading my (dot)net wide. :slightly_smiling_face:

Just noticed this has been answered on SO already - so I removed my reply as it wasnā€™t fully answering the problem, and duplicated the wrong SO answer :wink:

1 Like