How to implement decision tree with c# (visual studio 2008) - Help

前端 未结 2 1434
挽巷
挽巷 2021-01-31 19:57

I have a decision tree that i need to turn to a code in C#

The simple way of doing it is using if-else statements but in this solution i will need to create 4-5 nested c

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 20:10

    Below is the Tomas Petricek's code mentioned in the answer https://stackoverflow.com/a/3889544/5288052 .

    The zip containing all the source code of the book "Real-World Functional Programming" is available here https://www.manning.com/books/real-world-functional-programming .

    // Section 8.4.2 Decision trees in C#
    
    // Listing 8.15 Object oriented decision tree (C#)
    
    abstract class Decision {
      // Tests the given client 
      public abstract void Evaluate(Client client);
    }
    
    class DecisionResult : Decision {
      public bool Result { get; set; }
      public override void Evaluate(Client client) {
        // Print the final result
        Console.WriteLine("OFFER A LOAN: {0}", Result ? "YES" : "NO");
      }
    }
    
    
    // Listing 8.16 Simplified implementation of Template method
    class DecisionQuery : Decision {
      public string Title { get; set; }
      public Decision Positive { get; set; }
      public Decision Negative { get; set; }
      // Primitive operation to be provided by the user
      public Func Test { get; set; }
    
      public override void Evaluate(Client client) {
        // Test a client using the primitive operation
        bool res = Test(client);
        Console.WriteLine("  - {0}? {1}", Title, res ? "yes" : "no");
        // Select a branch to follow
        if (res) Positive.Evaluate(client);
        else Negative.Evaluate(client);
      }
    }
    
    static void MainDecisionTrees()
    {
      // The tree is constructed from a query
      var tree =
          new DecisionQuery
          {
            Title = "More than $40k",
            // Test is specified using a lambda function
            Test = (client) => client.Income > 40000,
            // Sub-trees can be 'DecisionResult' or 'DecisionQuery'
            Positive = new DecisionResult { Result = true },
            Negative = new DecisionResult { Result = false }
          };
    
      // Test a client using this tree
      // Create client using object initializer
      var john = new Client {
          Name = "John Doe", Income = 40000, YearsInJob = 1,
          UsesCreditCard = true, CriminalRecord = false 
        };
      tree.Evaluate(john);
    }
    
    private static void Main(string[] args)
    {
      MainDecisionTrees();
    }
    

提交回复
热议问题