2017-12-18 10 views
3

をカウントするために、相互再帰的なツリーを横断:私は木を横断しSecの出現回数をカウントする機能を作成しようとしてるF#が次のタイプを考える要素

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

4Sectionsが、この場合があるので、noOfSecs d、この場合の戻り4の場合と、Sectionsの数をカウントするDocumentを取っ

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]); 

機能:

は、次の例を考えます。私は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? 

答えて

4

あなたがその場合は0を返すことができるように0 Sec sがPar string以内にあります。 noOfSecsでは、最初の要素リストだけでなく、要素リスト内の各要素について、Secのケースを合計する必要があります。これにはList.sumByを使用できます。

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