2011年11月9日 星期三

神奇的linux/unix運算程式dc

dc是一個linux/unix指令列工具,完全運用stack做運算

用它可能沒什麼特別的好處(除了可能會很快之外。照理說這種純stack運算的語言可以做到飛快),但是如果想對程式運作有更深的了解,花點時間玩一下會有幫助,因為所有程式的函數呼叫控制都是用stack完成。

寫了一個hanoi tower自娛用,執行dc -f hanoi.dc就可以了
hanoi.dc的內容如下:
#function z : move source to destiny
[[ ]n ls n [ -> ] n ld n [ ]p]sz

#function Q : quit and clear top of stack n,s,d,i
[LnLsLdLi sbsbsbsb q]sQ

#function X(n,s,d,i) : hanoi tower function,
#n: number ; s: source ; d: destiny ; i: intermediate
[
 ln 0=Q
 ln 1- Sn
 li ld Si Sd ls Ss
 lXx
 lzx
 ln 1- Sn
 li ls Si Ss ld Sd
 lXx
 LnLsLdLi sbsbsbsb  #this line clears the top of parameter stacks
]SX

[number of disk:]P?
[start pillar:]P?
[destination pillar:]P?
[intermidiate pillar:]P?
SiSdSsSn
lXx