Question

This is a beginner question, as I'm still figuring out what the F# compiler errors mean and how to fix them.

I have the following F# code - and can't see why it will not work. It is based off the solution found here: F#: Recursive collect and filter over N-ary Tree

module TreeProblem_Solution1 =

    type TreeNode =
        | N of int * TreeNode list

    let rec filterTree (t : TreeNode) (predicate : int -> bool) =
       ()

    let test =
        TreeNode(1,[TreeNode(2,[])])

The error i get is under TreeNode(1,[TreeNode(2,[])]). I don't understand why this is causing a problem, when the nested TreeNode usage correctly displays the type and doesn't have any constructor problems, and I can also use this type as a method parameter.

Hopefully someone out there can shed some light on this, as I'm missing some vital insight.

Était-ce utile?

La solution

The reason that this is not working is that TreeNode is a type, not a constructor. You have defined a type TreeNode with a single union case called N. In order to create a value of a Discriminated Union, you must use the name of one of it's union cases. In this example, there is only one to use - N:

let test = N(1, [N(2, [])])

More info on unions can be found here.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top