如何在不强制实现的情况下找到惰性序列的长度? [英] How to find length of lazy sequence without forcing realization?

查看:14
本文介绍了如何在不强制实现的情况下找到惰性序列的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在阅读 O'reilly Clojure 编程书,其中关于惰性序列的部分内容如下:

I'm currently reading the O'reilly Clojure programming book which it's says the following in it's section about lazy sequences:

惰性序列有可能(尽管非常罕见)知道其长度,因此在不知道其内容的情况下将其作为计数的结果返回.

It is possible (though very rare) for a lazy sequence to know its length, and therefore return it as the result of count without realizing its contents.

我的问题是,这是如何做到的,为什么如此罕见?

My question is, How this is done and why it's so rare?

遗憾的是,本书在这一部分中没有具体说明这些内容.我个人认为在实现之前知道惰性序列的长度非常有用,例如,在同一页面中是使用 map 使用函数处理的惰性文件序列的示例.在实现序列之前知道可以处理多少文件会很好.

Unfortunately, the book does not specify these things in this section. I personally think that it's very useful to know the length of a lazy sequence prior it's realization, for instance, in the same page is an example of a lazy sequence of files that are processed with a function using map. It would be nice to know how many files could be processed before realizing the sequence.

推荐答案

我想这是因为通常有其他方法可以找出大小.

I suppose it's due to the fact that usually there are other ways to find out the size.

我现在能想到的唯一有可能做到这一点的序列实现是在已知大小的集合上的某种昂贵函数/过程的映射.

The only sequence implementation I can think of now that could potentially do that, is some kind of map of an expensive function/procedure over a known size collection.

一个简单的实现将返回底层集合的大小,同时将延迟序列的元素的实现(以及昂贵部分的执行)推迟到必要时.

A simple implementation would return the size of the underlying collection, while postponing realization of the elements of the lazy-sequence (and therefore execution of the expensive part) until necessary.

在这种情况下,我们可以事先知道被映射的集合的大小,并且可以使用它来代替惰性序列的大小.

In that case one knows the size of the collection that is being mapped over beforehand and can use that instead of the lazy-seq size.

有时它可能很方便,这就是为什么它不是不可能实现的原因,但我想很少有必要.

It might be handy sometimes and that's why it's not impossible to implement, but I guess rarely necessary.

这篇关于如何在不强制实现的情况下找到惰性序列的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆