Tree Representation in F#

后端 未结 2 1553
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 21:04

I\'m trying to implement a tree in F# using a list of tuples.
[a] where a = (string, [a])
Each node has a list of their childr

相关标签:
2条回答
  • 2020-12-17 21:20

    There are a couple ways to approach this, and Daniel's is nice. But here is another way (also using discriminant unions) to define a recursive data structure, this one being a bit closer to your own approach (though I think I may actually prefer Daniel's since the cases are more explicit):

    type tree<'a> =
        | Node of 'a * list<tree<'a>>
    
    let t3 = Node("a", [Node("b", [Node("c",[]); Node("d",[])]); Node("e", [Node("f",[]); Node("g",[])])])
    
    let rec checkstuff tple =
        match tple with
        | Node(_, []) -> true
        | Node(node, children) ->
            List.fold ( || ) false (List.map checkstuff children)
    
    0 讨论(0)
  • 2020-12-17 21:29

    Try changing your data structure a bit:

    type Tree =
      | Branch of string * Tree list
      | Leaf of string
    
    let t2 = Branch ("a", [Branch ("b", [Leaf "c"; Leaf "d"]); Branch ("e", [Leaf "f"; Leaf "g"])])
    
    let rec checkstuff tree =
        match tree with
        | Leaf _ -> true
        | Branch (node, children) ->
            List.fold ( || ) false (List.map checkstuff children)
    
    0 讨论(0)
提交回复
热议问题