F#遍历相互递归的树来计算元素

时间:2017-12-18 14:59:18

标签: f# tree

考虑以下类型:

type Title    = string
type Document = Title * Element list
and Element   = Par of string | Sec of Document

我试图创建一个遍历树并计算Sec出现次数的函数。

给出以下示例:

let s1  = ("section 1", [Par "Bla"])
let s2  = ("section 2", [Sec s21; Par "Bla"])
let s21 = ("subsection 2.1", [Par "Bla"])
let s3  = ("section 3", [Par "Bla"])
let doc = ("Compiler project", [Par "Bla"; Sec s1; Sec s2; Sec s3]);

Document计算Sections的数量的函数,noOfSecs d在这种情况下会返回4,因为4 Sections } 在这种情况下。我尝试了一些事情,但我有点卡住了,特别是当我点击Par时该怎么办:

let rec noOfSecs d =
    match d with
    | (_,[])    -> 0
    | (_,e::es) -> (findSecs e)
and findSecs = function
    | Sec(t,_::es) -> 1 + noOfSecs (t,es)
    | Par p        -> //What should we do here?

1 个答案:

答案 0 :(得分:4)

Sec中有Par string个,因此您可以为该情况返回0。在noOfSecs中,您需要对元素列表中每个元素的Sec个案例求和,而不仅仅是第一个。您可以使用List.sumBy

let rec noOfSecs (_, elems) =
    List.sumBy findSecs elems
and findSecs = function
    | Sec d -> 1 + noOfSecs d
    | Par p        -> 0