各程式語言對「宏」的支援是怎樣的?
lisp中的宏重要的一點是編譯期執行程式碼
Running code at read-time lets users reprogram Lisp‘s syntax; running code at compile-time is the basis of macros; compiling at runtime is the basis of Lisp’s use as an extension language in programs like Emacs; and reading at runtime enables programs to communicate using s-expressions, an idea recently reinvented as XML。
見:“What Made Lisp Different”
http://www。
paulgraham。com/diff。htm
l
除開lisp及其方言,
其他語言有
1。Forth及其方言, Forth稱之為‘編譯字“, Forth甚至有一種叫做Metacompiler的做法,也就是”Programs that write programs“, 具體的例子見retroForth的”complier variable“ :
http://
retroforth。org/docs/An_
Introduction_to_Retro。html
2。Template Haskell 見
http://www。
haskell。org/haskellwiki
/Template_Haskell
3。Julia 見
http://
julialang。org/manual/me
taprogramming/
4。C++的模板
5。 Nemerle 見
http://
nemerle。org/About/
其他的作為本身的擴充套件可以在編譯期操作語法的一些語言,比如
MetaLua :
http://
metalua。luaforge。net/qu
icktour。html
Converge :
http://
convergepl。org/about。ht
ml
Boo :
http://
docs。codehaus。org/displ
ay/BOO/Syntactic+Macros
(參考
http://
tackoverflow。com/questi
ons/6486597/are-there-any-non-lisp-dialects-that-allow-for-syntactic-abstraction
)
lisp和forth因為資料和程式碼一致(因此在執行時也異常強大,比如函式作為值)這兩門語言的宏的可讀性還可以,而剩下的語言就顯得很複雜
編譯期生成程式碼的一個優勢是速度,然而在強大的編譯器最佳化下速度基本上不是問題,這篇文章提到Smalltalk(同樣可以自己改變語法結構,但不支援macro) ”Can Smalltalk blocks be better than Lisp Macros?“ 見(牆外)
http://www。
cincomsmalltalk。com/use
rblogs/mls/blogView?entry=3289922530
所以可以做超程式設計的語言即使沒有宏還是可以接受的。
Scheme、Julia、Rust、Nim、Dylan、Nemerle 都有內建的 Hygienic Macro 支援
我在 PatEL 裡面也弄了 Hygienic Macro,是用文法閉包(Syntactic Closure)實現的,[macro-match] 會解理輸入的 form 並把每個子部分包上文法閉包。而 macro 本身則是一個函式,你願意的話每次宏展開時候把展開完的 ast 透過 http 上傳伺服器都行……
elixir 支援宏,是一個 ruby 愛好者開發的 erlang vm 語言
舉一個目前還不支援宏的例子。
Swift 3 不支援宏。理由很有趣:
Hygienic Macros and Compile-Time Evaluation: A first-class macro system, or support for compile-time code execution in general, is something we may consider in future releases。
We don't want the existence of a macro system to be a workaround that reduces the incentive for making the core language great.
From: Swift Evolution
翻譯一下,大意就是:我們不希望用宏系統來解決語言本身缺陷。
在 Swift Mailing List 裡面 Core Team 對宏的評價:
A macro system isn’t a ”slight“ compromise。
It's a major feature whose existence would forever change the way libraries are written in Swift.
It‘s not a feature to be taken lightly。 The C preprocessor is the single worst part of the C language from a tooling perspective, and even very well-designed macro systems (e。g。, Scala’s macro system is fairly interesting) have taken numerous iterations。
From: Swift Evolution Mailing List
宏本身是很有用的功能,但是更重要的是程式設計師會怎樣去使用宏。
看看x86組合語言的宏
上一篇:跟前男友分手之後想罵他怎麼辦?
下一篇:《傷寒論》第20條