Home > Software engineering >  Defining a lazy stream in Scala (translating a Racket example)
Defining a lazy stream in Scala (translating a Racket example)

Time:02-10

I was learning Racket (University of Washington Programming Languages course on Coursera) and there is an interesting example to define a lazy stream of values in Racket:

(define ones
  (lambda () (cons 1 ones)))

Basically this defines a function ones that returns a lambda that when called returns a tuple that the first element is 1 and the second element is the method itself.

I was trying to define this function in Scala but cannot get the typing right, there is some weird recursion going on:

def ones = () => (1, ones) // This complains that recursive function should have types
def ones: () => (Int, ???) = () => (1, ones) // What is the type here?

What's the correct type for this function?

CodePudding user response:

Basically this defines a function ones that returns a lambda that when called returns a tuple that the first element is 1 and the second element is the method itself.

Here we go: (Do not recommend, scala 2.1 only)

import scala.language.existentials

type T = () => (Int, () => A) forSome { type A <: (Int, () => A) }

def ones: T = () => (1, ones)

val (i1, f1) = ones()
val (i2, f2) = f1()
val (i3, f3) = f2()

println(i1, i2, i3) // get (1, 1, 1)

CodePudding user response:

Well (1, ones) is just a tuple, and a tuple has a fixed size so it can't be infinite, but you can just construct a LazyList just like in the racket example like this:

lazy val ones = 1 #:: ones

Or even simpler:

val ones = LazyList.continually(1)
  • Related