[賞書]代碼之髓:編程語言核心概念

代碼之髓:編程語言核心概念

花了一天摸完這本書

內容概括了程式設計裡面的一些議題,像是變數、Mix-IN、Trait等

稱不上有提到什麼深入的東西,但是姑且有提到一些有趣的技巧跟文章

這邊順便做個紀錄

Python

dis套件:用於觀看python函式stack vm下執行的程式

 >>> import dis
 >>> dis.dis(lambda x,y: x + y)
 1           0 LOAD_FAST                0 (x)
             3 LOAD_FAST                1 (y)
             6 BINARY_ADD
             7 RETURN_VALUE

ast套件:用於觀看特定代碼的ast結果

 >>> import ast
 >>> ast.dump(ast.parse("1 + 2"))
'Module(body=[Expr(value=BinOp(left=Num(n=1), op=Add(), right=Num(n=2)))])'

無條件捨去除法 //

 >>> 100 / 9.0
 11.11111111111111
 >>> 100 // 9.0
 11.0

STM(Software transactional memory)的參考資料

Software transactional memory
Software transactional memory on Haskell
A (brief) retrospective on transactional memory

Closure

摘錄自wiki

 >   closures (also lexical closures or function closures) are a technique for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a data structure storing a function[a] together with an environment:[1] a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or storage location the name was bound to at the time the closure was created

雖然這偶爾會使用這東西,但是看完這本書才對closure有更深的體悟
摘錄其中的例子

 function makeCounter(){
   var count = 0
     function push(){
         count++;
         console.log(count);
     }
   return push
 }
 c = makeCounter();
 c();  // print 1
 c();  // print 2

簡單的用途就是function另外宣告funcion的時候可以直接使用上層的變數
count就是上面提的free variable,他在push function宣告的時候binding並且associating在一起
好處是一般來說push找不到count變數的時候會去其他上層scope尋找該變數的宣告,但是一旦透過這種方式bind在一起之後
就不需要再去其他scope尋找該變數,達到類似close的效果

順便放一個偶然找到的Actor的paper
Foundations of Actor Semantics

comments powered by Disqus