我想用stream生成多个句子。我现在能造出1个句子。
def main(args: Array[String]): Unit = {
println((generateSentence take 1).mkString)
}
这是我到目前为止得到的结果
zIYow5ZJn92TjbcKbTvCf vaRNqZs80Fi4LcU7 8izJggPbjz9brbMtWmvo bGK
现在如果我想取两个句子,流将继续写入第一个句子
现在,我如何在该流中生成多个句子到一个数组(或一个列表)中呢?
我想把字体改成 Stream[List[String]]
但我不知道如何才能添加正确的生成方式(它给了我 Exception in thread "main" java.lang.StackOverflowError
)
使用流[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()
}
}
}
1条答案
按热度按时间nle07wnf1#
难点:)
您的方法生成无限递归:
是这样的:
这是一种方式,很明显,它称自己为无限。所以要解决你的问题,你可以用
toList
```def sentences : List[String] = {
generateWord take between(2, 25) toList
}