I have written a simple example for my scenario. I create a record type Switch
type State =
| On
| Off
with
member this.flip =
match this with
| On -> Off
| Off -> On
type Switch = { State : State }
and then I write a function that creates a copy of the record with one element changed
let flip switch = { switch with State = switch.State.flip }
To flip
many successive times I write
let flipMany times switch =
[1 .. times]
|> List.fold (fun (sw : Switch) _ -> flip sw) switch
If I want put these two functions on the record as methods, I write instead
type Switch =
{ State : State }
member this.flip =
{ this with State = this.State.flip }
member this.flipMany times =
[1 .. times]
|> List.fold (fun (sw : Switch) _ -> sw.flip) this
Is there anything wrong with doing this? Is it equally efficient? It feels a bit uncomfortable calling the function sw.flip
on a different object every single time.
Edit: this is just a simple example in order to explain my question. My question is on how the function flipMany
compares with the flipMany
method on the record. The implementation might be naive, but it is the same in both of cases.
flipMany
thru multiple calls toflip
- apparentlytimes%2 = 0
means do not flip, otherwise do one flip. – Diadem