Ways to write to F #

I wrote a simple example for my script. I create a switch record type

 type State = | On | Off with member this.flip = match this with | On -> Off | Off -> On type Switch = { State : State } 

and then I will write a function that creates a copy of the record with one element changed

 let flip switch = { switch with State = switch.State.flip } 

I write in flip many consecutive times

 let flipMany times switch = [1 .. times] |> List.fold (fun (sw : Switch) _ -> flip sw) switch 

If I want to put these two functions in the record as methods, I will 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 this? Is it equally effective? Feeling a little uncomfortable by calling the sw.flip function on a different object each time.

Edit: this is just a simple example to explain my question. My question is how flipMany function compare with the flipMany method in a record. The implementation may be naive, but in both cases it is the same.

+4
source share
1 answer

Your intention can be realized as easily as

 let flipMany times switch = match (times % 2) with | 1 -> { switch with State = switch.State.flip } | _ -> switch type Switch = { State : State } member this.Flip = { this with State = this.State.flip } member this.FlipMany times = match (times % 2) with | 1 -> this.Flip | _ -> this 

In a wider context of comparing static functions compared to the object method, the idiomatic method will adhere to the function option. The function has explicit arguments and should not depend on any lateral state, but the state of the arguments to obtain the value of the idempotent result. In contrast, an object method implicitly receives an instance of a class as an argument and can derive the result value not only from the arguments, but also based on the state of other fields of the class, which does not correspond to the idempotency property of a pure function.

To better understand this difference, it can help read the F # Component Design Guide and learn about the F # Core library design .

+10
source

All Articles