Mathematica/正規化
外觀
Mathematica 允許使用多種方法進行程式設計。考慮以下示例:我們想要一個 1 ≤ x ≤ 5、1 ≤ y ≤ 5 的 gcd(x, y) 值表。
最簡潔的方法是使用眾多專門函式之一
In[3]:= Array[GCD, {5, 5}]
Out[3]= {{1, 1, 1, 1, 1}, {1, 2, 1, 2, 1}, {1, 1, 3, 1, 1}, {1, 2, 1, 4, 1}, {1, 1, 1, 1, 5}}
至少還有三種方法可以實現這一點
In[4]:= Table[GCD[x, y], {x, 1, 5}, {y, 1, 5}]
Out[4]= {{1, 1, 1, 1, 1}, {1, 2, 1, 2, 1}, {1, 1, 3, 1, 1}, {1, 2, 1, 4, 1}, {1, 1, 1, 1, 5}}
一種APL 風格的方法
In[5]:= Outer[GCD, Range[5], Range[5]]
Out[5]= {{1, 1, 1, 1, 1}, {1, 2, 1, 2, 1}, {1, 1, 3, 1, 1}, {1, 2, 1, 4, 1}, {1, 1, 1, 1, 5}}
Outer對應於廣義的外積運算子。Range對應於 iota 運算子。Outer允許使用通用函式,無論它們是命名的,還是匿名的。匿名函式使用#n作為函式引數,並附加一個 &。上面的函式可以等效地指定為Outer[GCD[#1, #2] &, Range[5], Range[5]].
使用迴圈的方法
In[6]:= l1 = {}; (* initialize as empty list, since we want a list in the end *)
Do[l2 = {};
Do[l2 = Append[l2, GCD[i, j]], {j, 1, 5}];
l1 = Append[l1, l2], (* append the sublist, that is, the row *)
{i, 1, 5}]
In[7]:= l1
Out[7]= {{1, 1, 1, 1, 1}, {1, 2, 1, 2, 1}, {1, 1, 3, 1, 1}, {1, 2, 1, 4, 1}, {1, 1, 1, 1, 5}}
注意,此解決方案比之前的解決方案要大得多。