How to override a restricted method correctly

How to override the Zero method in the following code so that I can return Euro(0) to define in type Euro

 [<AbstractClass>] type Currency () = abstract member Zero<'T when 'T :> Currency > : unit -> 'T type Euro (value: int) = inherit Currency() member this.Value = value override this.Zero() = Euro(0) :> _ 
+5
source share
2 answers

Have you tried to raise the general restriction to the class level?

 [<AbstractClass>] type Currency<'T when 'T :> Currency<'T>>() = abstract member Zero : unit -> 'T type Euro (value: int) = inherit Currency<Euro>() member this.Value = value override this.Zero() = Euro(0) 

Although self-regulatory generics always seem strange to me, the way it will be, for example, in C #.

+7
source

F # also has a โ€œcollapse your own styleโ€ method. Basically, your abstract type members (instance and static) become fields of the "typeclass" record, and the values โ€‹โ€‹of this record are instances of typeclass. You may have a copy of the euro, a copy of the dollar, etc .:

 module Currency = type t<[<Measure>] 'a> = { zero : decimal<'a>; from : decimal -> decimal<'a> } /// Helper function to easily create typeclass instances for any /// currency. let make<[<Measure>] 'a> (curr_unit : decimal<'a>) : t<'a> = { zero = curr_unit - curr_unit; from = ((*) curr_unit) } [<Measure>] type euro let euro : t<euro> = make 1m<euro> [<Measure>] type dollar let dollar : t<dollar> = make 1m<dollar> 

The unique thing about F # is that the type parameter that is passed to each instance of typeclass can actually be a measure type that is suitable for currencies.

+1
source

Source: https://habr.com/ru/post/1264254/


All Articles