scala - 使用 scala 生成句子使用流
问题描述
我想使用 Stream 生成多个句子。我现在拥有的是我可以生成 1 个句子。
def main(args: Array[String]): Unit = {
println((generateSentence take 1).mkString)
}
这是我到目前为止的结果
zIYow5ZJn92TjbcKbTvCf vaRNqZs80Fi4LcU7 8izJggPbjz9brbMtWmvo bGK
现在如果我想取2个句子,流将继续写入第一个句子
现在我如何在该流中生成多个句子到一个数组(或一个列表)中。?
我想过将类型更改为,Stream[List[String]]
但我不知道如何以正确的方式添加生成的(它给了我Exception in thread "main" java.lang.StackOverflowError
)
使用 Stream[List[String]] 代码:
/**
* Generate one sentences between 2 and 25 words
* @return
*/
def generateSentence : Stream[List[String]] = {
def sentences : List[String] = {
sentences.::((generateWord take between(2, 25)).mkString) /* This line gave me the Exception StackOverflow */
}
Stream continually sentences
}
我写的原始代码
/**
* Generate one word between 2 and 25 char
* @return
*/
def generateWord: Stream[String] = {
def word : String = {
(Random.alphanumeric take between(2, 25)).mkString.concat(" ")
}
Stream continually word
}
/**
* Generate one sentences between 2 and 25 words
* @return
*/
def generateSentence : Stream[String] = {
def sentences : String = {
(generateWord take between(2, 25)).mkString
}
Stream continually sentences
}
/* This one is from the Random library, as it was introduced with 2.13 (so I just backported it into my 2.12)*/
def between(minInclusive: Int, maxExclusive: Int): Int = {
require(minInclusive < maxExclusive, "Invalid bounds")
val difference = maxExclusive - minInclusive
if (difference >= 0) {
Random.nextInt(difference) + minInclusive
} else {
/* The interval size here is greater than Int.MaxValue,
* so the loop will exit with a probability of at least 1/2.
*/
@tailrec
def loop(): Int = {
val n = Random.nextInt()
if (n >= minInclusive && n < maxExclusive) n
else loop()
}
loop()
}
}
}
解决方案
棘手的点:)
您的方法生成无限递归:
def sentences : List[String] = {
sentences.::((generateWord take between(2, 25)).mkString)
}
是这样的:
def sentences : List[String] = {
val result = sentences()
result.::((generateWord take between(2, 25)).mkString)
}
它是方式,很明显它无限地调用自己。所以为了解决你的问题,你可以使用toList
def sentences : List[String] = {
generateWord take between(2, 25) toList
}
推荐阅读
- vue.js - 如何将事件附加到 vuejs 中的变量
- android - 添加电子邮件和密码验证时应用程序崩溃
- java - 从 Java 生成的 Sha256 哈希与 OpenSSL 和 Sha256Sum 实用程序不同。为什么?
- javascript - 反应:this.state.renderData.filter 不是一个函数
- r - 如何在 R 中估计 Black-schole 或 GBM 的参数
- python - 如何使用 python django 将 OpenCV 输出发送到浏览器?
- python - 使用pyspark编写orc文件时如何避免解析错误?
- reactjs - 自定义反应分页与下拉选择返回额外的“-1”分页页面
- javascript - 如何在 JS 中实现 gsub 来替换字符串中的一组字符?
- gcdwebserver - 在 macOS/Cocoa 应用程序中启动 GCDWebServer 会冻结应用程序