
受到啟發有沒有辦法提取公式中使用的列?和伊恩@JMP評論。
dt = New Table( "Get Columns in Formula",
Add Rows( 20 ),
New Column( "H", Numeric, "Continuous", Format( "Best", 12 ), Formula( Random Uniform() ) ),
New Column( "W", Numeric, "Continuous", Format( "Best", 12 ), Formula( Random Uniform() ) ),
New Column( "D", Numeric, "Continuous", Format( "Best", 12 ), Formula( Random Uniform() ) ),
New Column( "V", Numeric, "Continuous", Format( "Best", 12 ), Formula( (:W * :H * :D) / 10 ) )
);
formula = dt:V << getformula();
// function to find leaves in formula that are columns in the table
findColumns = Function( {frm, cols},
{h = Head( frm ), n = N Arg( frm ), i, result = {}}, // local variables
If( n == 0, // head node has no children, it is a leaf
If( Contains( cols, Name Expr( h ) ), // is the leaf in the list of columns?
Insert Into( result, Name Expr( h ) ); // yes -> add to result
)
,
For( i = 1, i <= n, i++, // not a leaf, get children's results
Insert Into( result, Recurse( Arg( frm, i ), cols ) )
)
);
result// return the result
);
answer = findColumns( Name Expr( formula ), dt << GetColumnNames );
Show( formula, answer );
公式 = (:W * :H *
) / 10;
答案 = {:W, :H,
};
這尋找列第 10-22 行定義的函數採用兩個參數,弗羅姆,要檢查的公式,以及列,要提取的有效列名稱的清單。這頭範例表達式的 Divide(...) 它有兩個子表達式(答案來自精胺酸)。 if 語句看到有孩子並使用遞迴處理每個孩子的函數。多子有三個孩子。:W 子級沒有子級,且資料表中的列列表包含 :W,因此 :W 是插入到一個列表和傳回的列表,其中該列表被插入到另一個列表中。然後乘法子發送第二個精胺酸遞歸並附加 :H。最終10 (除法的第二個孩子)被送到遞歸,但不在列列表中,因此不會出現在答案中。
遞歸每次都需要付出一些努力。但它製作的程式看起來很簡單。