前面說(shuō)過(guò),需要一個(gè)語(yǔ)法糖來(lái)組織IO,并且在其中的一步產(chǎn)生錯(cuò)誤的時(shí)候立刻返回錯(cuò)誤?,F(xiàn)在我們看一段代碼:
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+"不是一個(gè)合法的整數(shù)。")
17 end;
18 end
19
20 def main123 = do
21 write "請(qǐng)輸入第一個(gè)整數(shù):";
22 a = readint;
23 write "請(qǐng)輸入第二個(gè)整數(shù):";
24 b = readint;
25 writeln ("它們的和是:" + itoa (a+b));
26 end
這三個(gè)函數(shù)的執(zhí)行結(jié)果是:
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 請(qǐng)輸入第一個(gè)整數(shù):1
9 請(qǐng)輸入第二個(gè)整數(shù):2
10 它們的和是:3
11 main123返回值:(system.success (system.pair <VOID> <USER>))
當(dāng)輸入的整數(shù)不是整數(shù)而是一個(gè)亂七八糟的字符串的時(shí)候,結(jié)果是這個(gè)樣子的:
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 請(qǐng)輸入第一個(gè)整數(shù):1
9 請(qǐng)輸入第二個(gè)整數(shù):fjkdla
10 main123返回值:(system.fail (system.ioemessage "輸入的字符串fjkdla不是一個(gè)合法的整數(shù)。"))
我們可以看一看readint編譯之后的代碼,就能知道為什么do-end可以及時(shí)返回錯(cuò)誤了:
1 (((>>=) read) (\text ->
2 select (atoi text) of
3 case (success num) : (return num)
4 case (fail remain) : (ioerror (((+) (((+) "輸入的字符串") text)) "不是一個(gè)合法的整數(shù)。"))
5 end))
其中return函數(shù)和ioerror函數(shù)的代碼如下:
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) 閱讀(1480)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
腳本技術(shù)