1

I want to generate multiple sentences using Stream. What I have now is I can generate 1 Sentences.

  def main(args: Array[String]): Unit = {
    println((generateSentence take 1).mkString)
  }

This is the result I have so far

  zIYow5ZJn92TjbcKbTvCf vaRNqZs80Fi4LcU7 8izJggPbjz9brbMtWmvo bGK

Now if I want to take 2 sentences, the stream will continue to write into the first sentence

Now how can I generate multiples sentences in that stream into an Array (or a List). ?

I thought of changing the type to Stream[List[String]] but I don't know how I can add the generated the correct way (It gave me Exception in thread "main" java.lang.StackOverflowError)

With Stream[List[String]] code :

  /**
   * 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
  }

Original Code I wrote

  /**
   * 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()
    }
  }
}
NoobZik
  • 87
  • 9

1 Answers1

1

Tricky point :)

Your method generates an infinite recursion:

def sentences : List[String] = {
      sentences.::((generateWord take between(2, 25)).mkString)
}

Is something like:

def sentences : List[String] = {
      val result = sentences()
      result.::((generateWord take between(2, 25)).mkString)
}

It is way, it is obvious that it calls itself infinitely. So to solve your problem, you can use toList

def sentences : List[String] = {
  generateWord take between(2, 25) toList
}
gianluca aguzzi
  • 1,734
  • 1
  • 10
  • 22