Skip to Content
Mathematica 錦囊妙計
book

Mathematica 錦囊妙計

by Sal Mangano
April 2014
Beginner to intermediate
830 pages
15h 21m
Chinese
GoTop Information, Inc.
Content preview from Mathematica 錦囊妙計
70
|
第二章
而這個做法失敗的原因則在於
state
只有在
Block
仍有效時才有定義,因為
Block
指
令 採 用 動 態 變 數 範 圍(dynamic scoping), 但 閉 包 需 要 的 是 詞 法 變 數 範 圍(lexical
scoping),你可能記得
Module
指令採用的便是詞法變數範圍,說不定使用
Module
指令
即可成功。
看起來似乎成功了,但缺點在於如果直接執行
counter
時,會出現下列結果。
[Page-070]
閉包中的
state
變數以
state$<n>
模擬,這是因為
Module
指令會在同名稱的全域變數已
存在的情況下,自動建立新變數,但新變數並沒有保護措施,使用者可以隨時隨地改變
它,這個缺陷讓使用
Module
指令的實作變得沒這麼優雅,而且此缺陷在 JavaScript 與
Lisp 語言中完全不會出現。
因此在本文的程式碼中使用了另一個策略,利用
HoldAll
屬性建立一個容器作為閉包的
詞法環境。因為變數與函數以未執行的形式儲存,所以不必擔心是否有全域變數使用了
相同的變數名稱。當閉包需要進行求值時,
evaluate
函數會使用
Block
環境建立區域變
數或函數,接著便將這些區域定義和已存數值的變數及函數進行連接,並呼叫適當的區
域函數。
實際上在 Mathematica 中實作閉包有何應用價值呢?計數器這種應用似乎太過於簡單,
但即便是計數器應用也能展現出一些重要的功能;首先,如果我們用全域變數做為計數
器,很可能會不小心存取到它,以閉包方式將計數器封裝,可限制其存
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.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Mathematica Cookbook

Mathematica Cookbook

Sal Mangano
人工智能技术与大数据

人工智能技术与大数据

Posts & Telecom Press, Anand Deshpande, Manish Kumar

Publisher Resources

ISBN: 9789863470106