简体   繁体   中英

Defining a lazy stream in Scala (translating a Racket example)

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?

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM