gpt4 book ai didi

f# - 如何遍历联合案例列表并访问每个案例的数据?

转载 作者:行者123 更新时间:2023-12-01 12:29:27 24 4
gpt4 key购买 nike

如何遍历联合案例列表并访问每个案例的数据?

我有这一行:

root.Neighbors |> Seq.filter(fun x -> print x)

但是,Neighbors 是一个列表:

Neighbors=[ One   { State=Survives; Neighbors=[] }
Two { State=Survives; Neighbors=[] }
Three { State=Survives; Neighbors=[] }
Four { State=Survives; Neighbors=[] }
Six { State=Survives; Neighbors=[] }
Seven { State=Survives; Neighbors=[] }
Eight { State=Survives; Neighbors=[] }
Nine { State=Survives; Neighbors=[] } ]

我需要访问邻居列表中每个邻居的状态。

但是,我收到以下错误:

The type 'Neighbor' does not match the type 'Cell' Type mismatch. Expecting a Neighbor -> unit but given a Cell -> unit

注意:我真的需要进行模式匹配才能访问所有邻居吗?

代码:

module GameOfLife

type Neighbor = | One of Cell
| Two of Cell
| Three of Cell
| Four of Cell

| Six of Cell
| Seven of Cell
| Eight of Cell
| Nine of Cell

and CauseOfDeath = | Underpopulated // Fewer than 2 live neighbors
| Overpopulated // More than 3 live neighbors

and State = | Dies of CauseOfDeath
| Survives // 2 or 3 live neighbors
| Resurected // Is dead and has 3 live neighbors

and Neighbors = Neighbor List

and Cell = { State:State; Neighbors:Neighbors }

let letThereBeLife() =
{ State=Survives; Neighbors=[ One { State=Survives; Neighbors=[] }
Two { State=Survives; Neighbors=[] }
Three { State=Survives; Neighbors=[] }
Four { State=Survives; Neighbors=[] }
Six { State=Survives; Neighbors=[] }
Seven { State=Survives; Neighbors=[] }
Eight { State=Survives; Neighbors=[] }
Nine { State=Survives; Neighbors=[] } ] }


let print (cell:Cell) =
printf "This cell %A\n%A" cell.State cell.Neighbors

let tick root =
root.Neighbors |> Seq.iter(print)

最佳答案

当您有一个复杂的区分联合,其中的案例在案例之间共享一些共同的状态,并且您想将它隐藏在一个更简单的界面后面时,一种技术是让一个成员隐藏模式匹配样板。

type Neighbor =
| One of Cell
...
| Nine of Cell
static member Cell (n: Neighbor) =
match n with
| One cell
...
| Nine cell -> cell

root.Neighbors |> Seq.iter (Neighbor.Cell >> print)

然而,正如其他人在评论中提到的那样,您真的应该重新考虑您的设计。这种巨大的 Neighbor 类型感觉就像你歧视了一个错误的维度。

关于f# - 如何遍历联合案例列表并访问每个案例的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35825845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com