我的Char Source Scala计划遇到了麻烦。要开发的包实现了文档源的概念。文档源类似于迭代器 但是以字符或单词形式生成其内容,以最方便的为基础 应用。与迭代器一样,单词和字符“在运行中”生成并且不存储。正确 文档源的实现应该能够
Trait CharSource:这个特性代表了我可以修改变换器混合的基本类型。它的来源 人物是抽象的。从它衍生的单词和单词,字符。 处理大型文档而不完全加载它们 在记忆中。 文档源提供两种方法: •chars:生成文档的内容作为字符的迭代器; •words:生成文档内容作为单词的迭代器。
这是我在迭代器上使用monaid运算符时遇到问题的地方。我尝试了foreach和map。
Class IteratorDocumentSource:
此类为我们提供了RichDocumentSource类型的默认实现。它可以用来混合 在各种组合的特征和观察结果。请注意,此类实现完整(“丰富”) 文档源接口,包括monadic运算符。
package document
class IteratorDocumentSource(iterator: Iterator[Char]) extends CharSource
with RichDocumentSource {
protected def source: Iterator[Char] = iterator
def foreach[A](f: (Char) => A): Unit = {
val it = iterator
for( x <- it ) yield f(x)
}
def map(f: (Char) => Char): IteratorDocumentSource = {
val it = iterator
val n = for( x <- it ) yield f(x)
}
new IteratorDocumentSource(n)
def flatMap(f: (Char) => TraversableOnce[Char]): IteratorDocumentSource =
???
def withFilter(f: (Char) => Boolean): IteratorDocumentSource = ???
}
// $Id: RichDocumentSource.scala 93 2017-03-26 18:46:10Z abcdef $
package document
/** A rich document source.
* It extends a regular document source with the so-called "monadic"
functions:
* `foreach`, `withFilter`, `map` and `flatMap`. Those operate at the
''character'' level, not on
* words.
*
* @see Iterator
trait RichDocumentSource extends DocumentSource {
/** Applies the given function to all the characters in the document. */
def foreach[A](f: (Char) => A): Unit
/** A new document obtained by applying the given transformation to all
the
characters of this
* document.
*/
def map(f: (Char) => Char): RichDocumentSource
/** A new document obtained by applying the given transformation to all the
characters of this
* document.
*/
def flatMap(f: (Char) => TraversableOnce[Char]): RichDocumentSource
/** A new document obtained by applying the given filter to all the
characters of this document.
*/
def withFilter(f: (Char) => Boolean): RichDocumentSource
}