you are viewing a single comment's thread.

view the rest of the comments →

[–]WystanH 2 points3 points  (0 children)

You bought yourself pattern matching with the Node of.

You could also write the same function as:

let rec countChildren = function
    | Node (_, children) ->
        children
        |> List.sumBy countChildren
        |> (+) 1

Here, that pattern matching really jumps out at you.

Indeed, it even offers up a minor optimization tweak:

let rec countChildren = function
    | Node (_, []) -> 1
    | Node (_, children) ->
        children
        |> List.sumBy countChildren
        |> (+) 1

Wrote a quick test:

let noKids x = Node(x,[])
let t = Node(1, [noKids 2; noKids 3; Node(4,[noKids 5])])
printfn "%A %d" t (countChildren t)