qed
qed

Reputation: 23094

Exit for loop as soon as condition satisfied

The following code hangs the repl:

(
  for {
    i <- 1 to 1000000
    j <- 2 to 1000000
    if i * i == j
  } yield i -> j
).take(1)

It seems the for expression is eagerly evaluated. Any solutions?

Upvotes: 1

Views: 97

Answers (1)

bjfletcher
bjfletcher

Reputation: 11508

I'd turn that into a stream:

(
    for {
        i <- Stream.range(1, 1000000)
        j <- Stream.range(2, 1000000)
        if i * i == j
    } yield i -> j
).take(1)

Upvotes: 1

Related Questions