我們知道,循環本身是沒有返回值的。所以在純函數式語言下,跟IO有關的循環才有足夠的副作用來產生價值。于是利用IO Monad,我們就可以實現循環了。循環是一個函數:
1 def ioloop count code =
2 let
3 def _loop index =
4 if (index>=count)
5 iovoid
6 ((code index) >>> (_loop (index+1)))
7 in _loop 0
這個函數輸入count,然后執行code。code接受一個參數代表目前循環的次數,循環次數從0到count-1之后結束。最后函數返回IO void。如果循環中出現錯誤,那么立刻返回錯誤。我們可以嘗試寫一段代碼:
1 def main125 = do
2 writeln "現在開始計算1到10的平方:";
3 ioloop 10 \index->do
4 number = return (index+1);
5 write ((itoa number) + "*" + (itoa number) + "=");
6 square = return (number * number);
7 writeln (itoa square);
8 end;
9 writeln "結束!";
10 end
執行結果如下:
1 現在開始計算1到10的平方:
2 1*1=1
3 2*2=4
4 3*3=9
5 4*4=16
6 5*5=25
7 6*6=36
8 7*7=49
9 8*8=64
10 9*9=81
11 10*10=100
12 結束!
13 main125返回值:(system.success (system.pair <VOID> <USER>))
posted on 2008-12-15 07:56
陳梓瀚(vczh) 閱讀(2155)
評論(2) 編輯 收藏 引用 所屬分類:
腳本技術