F# 如何迭代联合案例列表并访问每个案例';谁的数据?

F# 如何迭代联合案例列表并访问每个案例';谁的数据?,f#,conways-game-of-life,F#,Conways Game Of Life,如何迭代工会案例列表并访问每个案例的数据? 我有一句话: root.Neighbors |> Seq.filter(fun x -> print x) 但是,邻居是一个列表: Neighbors=[ One { State=Survives; Neighbors=[] } Two { State=Survives; Neighbors=[] } Three { State=Survives; Neighbors=[] }

如何迭代工会案例列表并访问每个案例的数据?

我有一句话:

root.Neighbors |> Seq.filter(fun x -> print x)
但是,邻居是一个列表:

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=[] } ]
我需要访问邻居列表中每个邻居的状态

但是,我收到以下错误:

“邻居”类型与“单元”类型不匹配的类型不匹配。 需要一个邻居->单元,但给定了一个单元->单元

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

代码:

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)

然而,正如其他人在评论中提到的,你应该真正重新思考你的设计。这种巨大的邻居类型让人感觉你在一个错误的维度上进行了歧视。

你的问题的答案是肯定的,所以我必须陈述每个工会案例来执行相同的操作?类似于
root.neights |>fun t->t.neights |>…
这可能是对你的反馈,让你重新考虑你的设计。八个类似的案例是解决这个特定问题的最佳方式吗?同意,如果我的评论被认为是试图提供一个有用的提示,我很抱歉@JohnPalmer是正确的,如果您的设计规定了这八种情况,那么您需要在它们上进行模式匹配。我明白,如果这看起来像样板(我也这么认为),但我想说的是,也许有另一种设计使这个问题变得毫无意义。