4

I am trying to write a generic iterator that coputes the Fibonacci sequence:

def FibIter[T](fst:T , snd:T)(implicit num:Numeric[T]) = new Iterator[T] {
  var fn1 = fst
  var fn2 = snd
  def hasNext = true
  def next() = {
    val ret = fn1
    fn1 = fn2
    fn2 = num.plus(ret,fn2)
    ret
  }
}

However, the compiler complains about the first two variable assignments:

Parameter type in structural refinement may not refer to an abstract type defined outside that refinement

Does anyone has an idea how to solve this problem? Thank you very much!

richj
  • 7,499
  • 3
  • 32
  • 50
Manuel Schmidt
  • 2,429
  • 1
  • 19
  • 32
  • 2
    See this: http://stackoverflow.com/questions/7830731/parameter-type-in-structural-refinement-may-not-refer-to-an-abstract-type-defin – foowtf Nov 14 '11 at 23:38
  • 2
    It's not an answer to your question, but `Iterator.iterate(fst, snd) { case (i, j) => (j, num.plus(i, j)) }.map(_._1)` is arguably a nicer way to write this. – Travis Brown Nov 15 '11 at 00:31
  • @Travis, thx. I just started to learn scala and it is very helpfull to see code like yours – Manuel Schmidt Nov 15 '11 at 03:24

1 Answers1

5

It seems you can workaround this by using a dedicated class

class FibIter[T](fst:T , snd:T)(implicit num:Numeric[T]) extends Iterator[T] {
  var fn1 = fst
  var fn2 = snd
  def hasNext = true
  def next() = {
    val ret = fn1
    fn1 = fn2
    fn2 = num.plus(ret,fn2)
    ret
  }
}
0__
  • 66,707
  • 21
  • 171
  • 266
  • As user1005631 pointed out, this is explained in http://stackoverflow.com/questions/7830731/parameter-type-in-structural-refinement-may-not-refer-to-an-abstract-type-defin – 0__ Nov 15 '11 at 02:03