我为我的场景编写了一个简单的示例。我创建了一个记录类型
为了连续多次翻转,我写下以下代码:
如果我想将这两个函数作为方法记录下来,那么我应该写成:
Switch
。type State =
| On
| Off
with
member this.flip =
match this with
| On -> Off
| Off -> On
type Switch = { State : State }
然后我写了一个函数,它可以创建一份记录的副本,并将其中一个元素更改。
let flip switch = { switch with State = switch.State.flip }
为了连续多次翻转,我写下以下代码:
flip
。let flipMany times switch =
[1 .. times]
|> List.fold (fun (sw : Switch) _ -> flip sw) switch
如果我想将这两个函数作为方法记录下来,那么我应该写成:
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
这样做有什么问题吗?这样做同样有效吗?每次在不同的对象上调用函数sw.flip
感觉有点不舒服。
编辑:这只是一个简单的例子,为了解释我的问题。我的问题是如何比较函数flipMany
与记录上的flipMany
方法。实现可能是天真的,但在这两种情况下是相同的。
flip
来实现flipMany
- 显然,如果times%2 = 0
则不翻转,否则进行一次翻转。 - Gene Belitski