Skip to Main Content
Mathematica 錦囊妙計
book

Mathematica 錦囊妙計

by Sal Mangano
April 2014
Beginner to intermediate content levelBeginner to intermediate
830 pages
15h 21m
Chinese
GoTop Information, Inc.
Content preview from Mathematica 錦囊妙計
2.9 使用 Fold 指令取代遞迴運算
|
55
以下使用視覺化呈現
foldr
foldl
的差異,其目標函數為
List
指令。可明顯看出標示
b
c
的版本是相同的,這證明了 Haskell
foldl
指令與 Mathematica
Fold
指令是相
同的。[Page-055]
ch02.indd 55 2014/4/2 上午 03:32:26
56
|
第二章
你可以使用
Fold
指令與遞迴的關係,進行更複雜的應用。例如,Mathematica 說明文件
中提供一個範例,利用
Fold
指令運算所有可能的子串列和。[Page-056]
當我第一次見到這個程式時,一時無法理解為什麼這個程式碼行得通,然而,藉由將其
轉換為遞迴函數定義,較容易理解此程式是如何運作的。
第一列的程式碼很直觀,空串列的子串列和只能為零。第二列則定義串列可能的子串列
和會是三個集合的聯集,分別為:串列的第一個元素、除去第一元素剩餘串列的可能子
串列和以及兩者的和。第三個集合
(First[l] + uniqueSums[Rest[l]])
提供我們此程式
可行的線索,它將純量與向量相加,即第一個元素將與剩餘串列的可能子串列和相加。
很明顯地,此遞迴函數並非最佳化版本,因為遞迴內部呼叫了自己兩次(可使用暫存變
數避免),但本文重點在於,你
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Ubuntu for Non-Geeks, 4th Edition

Ubuntu for Non-Geeks, 4th Edition

Rickford Grant, Phil Bull

Publisher Resources

ISBN: 9789863470106