【问题标题】:Generate sentences usign streams using scala使用 scala 使用流生成句子
【发布时间】:2021-07-08 21:21:02
【问题描述】:

我想使用 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()
    }
  }
}

【问题讨论】:

  • generateSentence.take(2).foreach(println) ?或generateSentence.take(2).toList
  • 请注意,自 Scala 2.13 起,Stream 已被弃用,取而代之的是 LazyList
  • 是的,Spark 在 2.13 中不受支持,这对我来说很不幸,这就是我使用 Stream 写作的原因

标签: scala generate scala-streams


【解决方案1】:

棘手的问题:)

你的方法会产生一个无限递归:

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
}

【讨论】:

  • 这对我来说是一个很好的开始,谢谢,我稍后会进一步研究
猜你喜欢
  • 2020-09-11
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
相关资源
最近更新 更多