2009-08-08 22 views
1

我有以下代碼。我構建了一個表達式樹,我被困解析它找到的結果幫助解析我自己的表達式樹,C#

你會發現我的代碼

public enum OpertaionType { add, sub, div, mul} 

public class Node { 
    public Node(Node lhs, Node rhs, OpertaionType opType, int index) { 
     this.lhs = lhs; 
     this.rhs = rhs; 
     this.opType = opType; 
     this.index = index; 
    } 
    Node lhs; 
    Node rhs; 
    OpertaionType opType; 
    int index; 
} 
class Program 
{ 
    static void Main(string[] args) 
    { 
     // I don't want this to be part of the node data structure 
     // because in the actual implementation I will end up referencing an 
     // array of data 

     int[] value = new int[5]; 

     Node[] nodes = new Node[value.Length]; 
     for (int i = 0; i < value.Length; i++) 
     { 
      value[i] = i+1; 
      nodes[i] = new Node(null, null, 0, i); 
     } 



     // suppose I constructed the tree like that 
     // note that the end nodes are marked by non-negative index that indexes the 
     // values array 

     Node a = new Node(nodes[0], nodes[1], OpertaionType.add, -1); 
     Node b = new Node(nodes[2], a, OpertaionType.mul, -1); 
     Node c = new Node(b, nodes[3], OpertaionType.div, -1); 

     // How can I find the result of Node c programatically 
     // such that the result is (a[2]*(a[0]+a[1]))/a[3] = 9/4 

    } 
} 
+0

這功課嗎? – 2009-08-08 16:41:34

+0

heyy堅持..你可能會在這裏分享你的驚人知識! – mustafabar 2009-08-08 16:45:44

+0

沒有馬丁它不是 – mustafabar 2009-08-08 16:49:46

回答

1

內的細節對於一個簡單的基本介紹到C#3.0本身的表達式樹,例如見here;不幸的是,我不知道關於這個主題的真正廣泛和深刻的文本(也許是一本書..?)。

至於你自己的手卷格式,你可以通過遞歸來評估它;在僞代碼:

def valof(node): 
    if node.index >= 0: 
    return whateverarray[node.index] 
    L = valof(node.lhs) 
    R = valof(node.rhs) 
    if node.opType == add: 
    return L + R 
    if node.opType == mul: 
    return L * R 
    # etc etc 

作爲進一步的扭曲,因爲你似乎想分數的結果,而輸入值是整數,記住使用一小部分/有理數類型的計算 - 不知道C#自帶一個,但最糟糕的情況是你可以在網上找到很多;-)。

+0

謝謝亞歷克斯..這工作得很好 – mustafabar 2009-08-09 06:48:58

+0

內置表達式樹不可序列化...我想通過它的WCF服務:)我不知道這是否可以acheivable – mustafabar 2009-08-09 06:49:53

3

需要遞歸算法,傳遞的值陣列(代碼未經測試):

class Node{ 
    //... 
    double compute(int[] values){ 
    if(index >= 0) 
     return values[index]; // leaf node; value stored in array 
    switch(opType){ 
     case add: return lhs.compute(values)+rhs.compute(values); 
     case sub: return lhs.compute(values)-rhs.compute(values); 
     case div: return lhs.compute(values)*rhs.compute(values); 
     case mul: return lhs.compute(values)/rhs.compute(values); 
    } 
    throw new Exception("unsupported operation type"); 
    } 
} 

注意,這以雙所有計算;如果你真的想要9/4,你需要使用一個合理的類型。