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