Tail-recursive bounded stream of pairs of integers (Scala)?

前端 未结 2 979
一生所求
一生所求 2020-12-15 07:58

I\'m very new to Scala, so forgive my ignorance! I\'m trying to iterate of pairs of integers that are bounded by a maximum. For example, if the maximum is 5, then the iterat

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 08:24

    Maybe an Iterator is better suited for you?

    class PairIterator (max: Int) extends Iterator [(Int, Int)] {
      var count = -1
      def hasNext = count <= max * max 
      def next () = { count += 1; (count / max, count % max) }
    }
    
    val pi = new PairIterator (5)
    pi.take (7).toList 
    

提交回复
热议问题