使用生成器和序列做的有趣事情
当您想要一个接一个地获取序列的一部分时,还有其他人觉得迭代器不够用吗?
也许我应该开始用 F# 编写代码(顺便说一句,任何人都知道 F# 是否使用惰性求值),但我发现自己想要一种以非常独特的方式提取序列的方法。
例如
// string.Split implemented as a generator, with lazy evaluation
var it = "a,b,c".GetSplit(',').GetEnumerator();
it.MoveNext();
var a = it.Current;
it.MoveNext();
it.MoveNext();
var c = it.Current;
,这可行,但我不喜欢它,它很丑。那么我可以这样做吗?
var it = "a,b,c".GetSplit(',');
string a;
var c = it.Yield(out a).Skip(1).First();
这样更好。但我想知道是否有另一种方法来概括相同的语义,也许这已经足够好了。通常我正在做一些嵌入的字符串解析,这时就会出现这个问题。
还有一种情况是,我希望使用一个序列到特定点,然后基本上分叉它(或克隆它,这样更好)。就像这样
var s = "abc";
IEnumerable<string> a;
var b = s.Skip(1).Fork(out a);
var s2 = new string(a.ToArray()); // "bc"
var s3 = new string(b.ToArray()); // "bc"
最后一个,一开始可能没那么有用,我发现它相当方便地解决了回溯问题。
我的问题是我们需要这个吗?或者它是否已经以某种方式存在而我只是错过了?
Does anyone else feel that the iterators are coming up short when you want to take a part a sequence piece by piece?
Maybe I should just start writing my code in F# (btw anybody knows if F# uses lazy evaluation) but I've found myself wanting a way to pull at a sequence in a very distinct way.
e.g.
// string.Split implemented as a generator, with lazy evaluation
var it = "a,b,c".GetSplit(',').GetEnumerator();
it.MoveNext();
var a = it.Current;
it.MoveNext();
it.MoveNext();
var c = it.Current;
That works, but I don't like it, it is ugly. So can I do this?
var it = "a,b,c".GetSplit(',');
string a;
var c = it.Yield(out a).Skip(1).First();
That's better. But I'm wondering if there's another way of generalizing the same semantic, maybe this is good enough. Usually I'm doing some embedded string parsing, that's when this pops out.
There's also the case where I wish to consume a sequence up to a specific point, then basically, fork it (or clone it, that's better). Like so
var s = "abc";
IEnumerable<string> a;
var b = s.Skip(1).Fork(out a);
var s2 = new string(a.ToArray()); // "bc"
var s3 = new string(b.ToArray()); // "bc"
This last one, might not be that useful at first, I find that it solves backtracking issues rather conveniently.
My question is do we need this? or does it already exist in some manner and I've just missed it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
序列基本上可以正常工作,即提供一个简单的接口,可以根据需要生成值流。如果您有更复杂的需求,那么欢迎您使用更强大的界面。
例如,您的字符串示例看起来可以受益于被编写为解析器:即,一个使用流中的字符序列并使用内部状态来跟踪它在流中的位置的函数。
Sequences basically work OK at what they do, which is to provide a simple interface that yields a stream of values on demand. If you have more complicated demands then you're welcome to use a more powerful interface.
For instance, your string examples look like they could benefit being written as a parser: that is, a function that consumes a sequence of characters from a stream and uses internal state to keep track of where it is in the stream.