前面說過,需要一個語法糖來組織IO,并且在其中的一步產生錯誤的時候立刻返回錯誤。現在我們看一段代碼:
1 def main121 = do
2 writeln "Hello World!";
3 writeln "Hello World!";
4 writeln "Hello World!";
5 end
6 def main122 = do
7 write "Enter your name:";
8 name = read;
9 writeln ("Hello "+name+".");
10 end
11
12 def readint = do
13 text = read;
14 select atoi text of
15 case success num : return num
16 case fail remain : ioerror ("輸入的字符串"+text+"不是一個合法的整數。")
17 end;
18 end
19
20 def main123 = do
21 write "請輸入第一個整數:";
22 a = readint;
23 write "請輸入第二個整數:";
24 b = readint;
25 writeln ("它們的和是:" + itoa (a+b));
26 end
這三個函數的執行結果是:
1 Hello World!
2 Hello World!
3 Hello World!
4 main121返回值:(system.success (system.pair <VOID> <USER>))
5 Enter your name:vczh
6 Hello vczh.
7 main122返回值:(system.success (system.pair <VOID> <USER>))
8 請輸入第一個整數:1
9 請輸入第二個整數:2
10 它們的和是:3
11 main123返回值:(system.success (system.pair <VOID> <USER>))
當輸入的整數不是整數而是一個亂七八糟的字符串的時候,結果是這個樣子的:
1 Hello World!
2 Hello World!
3 Hello World!
4 main121返回值:(system.success (system.pair <VOID> <USER>))
5 Enter your name:vczh
6 Hello vczh.
7 main122返回值:(system.success (system.pair <VOID> <USER>))
8 請輸入第一個整數:1
9 請輸入第二個整數:fjkdla
10 main123返回值:(system.fail (system.ioemessage "輸入的字符串fjkdla不是一個合法的整數。"))
我們可以看一看readint編譯之后的代碼,就能知道為什么do-end可以及時返回錯誤了:
1 (((>>=) read) (\text ->
2 select (atoi text) of
3 case (success num) : (return num)
4 case (fail remain) : (ioerror (((+) (((+) "輸入的字符串") text)) "不是一個合法的整數。"))
5 end))
其中return函數和ioerror函數的代碼如下:
1 func return T :: T -> IO T
2 def return x e = success (pair x e)
3
4 func ioerror T :: string -> IO T
5 def ioerror s = \env->fail(ioemessage s)
posted on 2008-12-15 06:22
陳梓瀚(vczh) 閱讀(1475)
評論(0) 編輯 收藏 引用 所屬分類:
腳本技術