2007-09-10
探讨生成器的几种实现形式
关键字: Lysee 编程
生成器可以看作为程序提供连续输入的流,输入类型通常固定为一种(比如整型),当然也可以是任意多的不同类型,下面探讨几种生成器的实现方法,题目是生成1...N的整形值:
一、大家都会的:
二、基于类实现:
三、基于对象实现:
四、使用函数闭包:
五、使用YIELD:
六、使用CURRY:
七、返回不同的类型:
实现生成器确实很有意思,一时兴起就写了了几种实现形式,哪位老大还知道别的形式,不妨补充一下,谢谢了!
一、大家都会的:
// 代码
public int seed = 0;
public int generator()
{
++ seed;
return seed;
}
// 使用
10.times { = generator() + " " };
// 结果
1 2 3 4 5 6 7 8 9 10
二、基于类实现:
// 代码
public class Generator
{
public int _seed;
public int next()
{
this._seed = this._seed + 1;
return this._seed;
}
}
public Generator generator = Generator();
// 使用
10.times { = generator.next() + " " };
// 结果
1 2 3 4 5 6 7 8 9 10
三、基于对象实现:
// 代码
public object generator
{
public int _seed;
public int next()
{
this._seed = this._seed + 1;
return this._seed;
}
}
// 使用
10.times { = generator.next() + " " };
// 结果
1 2 3 4 5 6 7 8 9 10
四、使用函数闭包:
// 代码
public function init(int seed)
{
return { ++ seed; return seed };
}
function generator = init(0);
// 使用
10.times { = generator() + " " };
// 结果
1 2 3 4 5 6 7 8 9 10
五、使用YIELD:
// 代码
public int init(int seed)
{
while(true) {
++ seed;
return seed
};
}
function generator = sys::yield(init, [0]);
// 使用
10.times { = generator() + " " };
// 结果
1 2 3 4 5 6 7 8 9 10
六、使用CURRY:
// 代码
public int init(int seed)
{
return seed + __func__.execTimes;
}
function generator = sys::curry(init, [0]);
// 使用
10.times { = generator() + " " };
// 结果
1 2 3 4 5 6 7 8 9 10
七、返回不同的类型:
// 代码
public variant init(string s)
{
return s;
return length(s);
return {|string who| = who, "said:", s, eol};
}
function generator = sys::yield(init, ["hello world"]);
// 使用
= "length \"" + generator() + "\" is " + generator(), eol;
generator()("LYSEE");
// 结果
length "hello world" is 11
LYSEE said: hello world
实现生成器确实很有意思,一时兴起就写了了几种实现形式,哪位老大还知道别的形式,不妨补充一下,谢谢了!
- 10:44
- 浏览 (363)
- 论坛浏览 (441)
- 评论 (0)
- 相关推荐
发表评论
该博客是同时发布到论坛的,无法评论在论坛已被锁定的帖子
- 浏览: 3457 次
- 性别:

- 来自: 郑州

- 详细资料
搜索本博客
最近加入圈子
最新评论
-
lysee 官方网站开张营业
RednaxelaFX 2008-05-20引用啊,来迟了。刚刚有空 ...
-- by libudi -
lysee 官方网站开张营业
啊,来迟了。刚刚有空在JavaEye逛的时候才发觉Lysee有新进展了,加油! ...
-- by RednaxelaFX -
lysee 官方网站开张营业
我认为,托管资源目前来说,主要是内存。不是handle。所谓托管资源,也就是由g ...
-- by 梁利锋 -
lysee 官方网站开张营业
猜的不错的话 GC 回收的托管资源,比如,链表、字典、内存流之类的,通常都是非托 ...
-- by libudi -
lysee 官方网站开张营业
google 了一下 Notification 和 FreeNotificati ...
-- by 梁利锋






评论排行榜