随笔-341  评论-2670  文章-0  trackbacks-0
    前面说过,需要一个语法糖来组织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) 阅读(1453) 评论(0)  编辑 收藏 引用 所属分类: 脚本技术

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理