0

In relation to this question: What is a better way to model a treeNode?

I am thinking how to define similar trees in c# so that they would have the same difference. So, having

type TreeNode = | TreeNode of int * (TreeNode option) * (TreeNode option) * (TreeNodeoption)

type Node = | Node of int * Node * Node
            | None

According to @Tomas Petricek answer, the difference between those two types is that the first one doesn't allow to create a truly empty tree. A TreeNode would always have a int value in it.

What is the way to express this in C#?

Community
  • 1
  • 1
Grzegorz Sławecki
  • 1,727
  • 14
  • 27
  • Float? Wouldn't it have an int? – harold Jun 26 '14 at 10:14
  • Yes, You're right, i changed "float" to "int". – Grzegorz Sławecki Jun 26 '14 at 10:38
  • If you want you can express it just as the F# compiler handles it: with a base-class TreeNode/Node and subclasses for the cases (ok - only cases with data) - But C# has no good pattern matching so you gain almost nothing ... better look for thinks like Visitor-pattern etc. ... or just use F# ;) – Random Dev Jun 26 '14 at 11:13

1 Answers1

2

This is really just a particular case of a Discriminated Union in C#. Take a look here for a good discussion on that.

Community
  • 1
  • 1
Christopher Stevenson
  • 2,843
  • 20
  • 25
  • Well, i thought, that maybe there's some less verbose solution than implementing a union equivalent and then using it, but obviously, this is a good answer and it's the only one so far. – Grzegorz Sławecki Jun 27 '14 at 11:34