cyclic definitions error during IntelliJ worksheet

Viewed 33

I have updated IntelliJ Idea Ultimate and scala plugin, it's working ok so far with sbt to build some projects.

Using a scala worksheet in REPL Interactive mode, I put in some code from a course lecture,

val rand = java.util.Random()

trait Generator[+T]:
  def generate(): T
  def map[S](f: T => S) = new Generator[S]:
    def generate() = f(Generator.this.generate())
  def flatMap[S](f: T => Generator[S]) = new Generator[S]:
    def generate() = f(Generator.this.generate()).generate()
    
val integers = new Generator[Int]:
  def generate() = rand.nextInt()

val booleans = for x <- integers yield x > 0

def single[T](x: T): Generator[T] = new Generator[T]:
  def generate() = x

def lists: Generator[List[Int]] =
  for
    isEmpty <- booleans
    list <- if isEmpty then emptyLists else nonEmptyLists // *1
  yield list

def emptyLists = single(Nil)

def nonEmptyLists =
  for
    head <- integers
    tail <- lists // *2
  yield head :: tail

At *1 I got

4 |    list <- if isEmpty then emptyLists else nonEmptyLists
  |                            ^^^^^^^^^^
  |                            Not found: emptyLists
4 |    list <- if isEmpty then emptyLists else nonEmptyLists
  |                                            ^^^^^^^^^^^^^
  |                                            Not found: nonEmptyLists

At *2 I got

4 |    tail <- lists
  |            ^^^^^
  |            Not found: lists

Maybe some tweak to the settings I haven't found yet?

1 Answers

Put everything in an object.

This way the 2 defs that depends on each other will be available at the same time.

IntelliJ worksheets do not like such definitions as they are "evaluated" one by one. You cannot define 2 depending on one the other at the top-level, they need to be encapsulated.

Related