Creating hierarchical data using closure in C #?

I am trying to create hierarchical data using closure in C #. I have a Method " Pair " that looks like this:

  public static Func<string, int> Pair(int x,Func<string, int> y)
    {

        Func<string, int> pair =
               (a) =>
               {
                   if (a == "con") return x;
                   if (a == "crd") return y("con");
                   throw new Exception();
               };

        return pair;
    }

      

Than I will create my Hierarchical data as below:

      var pair = Pair(1,
                        Pair(2,
                              Pair(3,
                                    Pair(4,null))));

      

which when visually presented looks like this:

I know this approach is wrong because I cannot get / print all the values ​​stored in a pair. I cannot do something like this:

 public static void Print(Func<string, int> pair)
    {
        if (pair("crd") == null) return;
        Console.WriteLine(pair("con"));
        Print(pair("crd")); //Compilation Error
    }

      

Can someone tell me how to do this in C #.

+3


source to share


1 answer


The problem is that your pair's closure must return two different types of objects: int if you ask for "con", and the next closure on the line if you ask for "crd".

Here's one possible implementation:

Use a speaker so you can come back.

public static Func<string, dynamic> Pair(int x, Func<string, dynamic> y)
{
    Func<string, dynamic> pair =
           (a) =>
           {
               if (a == "con") return x;
               if (a == "crd") return y;
               throw new Exception();
           };

    return pair;
}

public static void Print(Func<string, dynamic> pair)
{
    while (true)
    {
        var next = pair("crd");
        Console.WriteLine((next == null ? "-":"+") +"> " + pair("con"));
        if (next != null)
        {
            Console.WriteLine("|");
            pair = (x) => next(x);
            continue;
        }
        break;
    }
}

      



Test:

var pair = Pair(1,
            Pair(2,
                  Pair(3,
                        Pair(4, null))));

Print(pair);

      

output:

+> 1
|
+> 2
|
+> 3
|
-> 4

      

+1


source







All Articles