I'm learning Scala as my first functional-ish language. As one of the problems, I was trying to find a functional way of generating the sequence S up to n places. S is defined so that S(1) = 1, and S(x) = the number of times x appears in the sequence. (I can't remember what this is called, but I've seen it in programming books before.)
In practice, the sequence looks like this:
S = 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7 ... I can generate this sequence pretty easily in Scala using an imperative style like this:
def genSequence(numItems: Int) = { require(numItems > 0, "numItems must be >= 1") var list: List[Int] = List(1) var seq_no = 2 var no = 2 var no_nos = 0 var num_made = 1 while(num_made < numItems) { if(no_nos < seq_no) { list = list :+ no no_nos += 1 num_made += 1 } else if(no % 2 == 0) { no += 1 no_nos = 0 } else { no += 1 seq_no += 1 no_nos = 0 } } list } But I don't really have any idea how to write this without using vars and the while loop.
Thanks!
Stream.continually(x).take(S(x)).toList. Write a recursive function using this as part of its definition - I just don't know Scala well enough to tell you what it should be.1, 0, 0, 0, ...also satisfies your criteria.