for loops with range range

36 views
Skip to first unread message

david.h...@vidhance.com

unread,
Nov 13, 2015, 9:16:01 AM11/13/15
to ooc-lang
range := 0 .. 5
for (i in range) {
i toString() println()
}

Is this supposed to work?

Amos Wenger

unread,
Nov 13, 2015, 10:42:05 AM11/13/15
to david.h...@vidhance.com, ooc-lang
looks reasonable, I'd expect it to work.


--
You received this message because you are subscribed to the Google Groups "ooc-lang" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ooc-lang+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jeremy Clarke

unread,
Nov 13, 2015, 12:07:06 PM11/13/15
to Amos Wenger, david.h...@vidhance.com, ooc-lang
I went and added an iterator() method to Range in lang/Numbers.ooc, and then David's code works just fine :)

I was quite surprised about this, because Range is a cover so I couldn't see any way to implement the Iterable class, but it turns out this is not needed.

Should I make a pull request with this in the SDK?


Range: cover {

    min, max: Int

    new: static func (.min, .max) -> This {
        this : This
        this min = min
        this max = max
        return this
    }

    reduce: func (f: Func (Int, Int) -> Int) -> Int {
        acc := f(min, min + 1)
        for(i in min + 2..max) acc = f(acc, i)
        acc
    }
   
    iterator: func -> RangeIterator<Int> {
        RangeIterator<Int> new(this)
    }
   
}

RangeIterator: class <T> extends Iterator<T> {
    i: Int
    range: Range
   
    init: func (=range) {
        i = range min
    }
   
    hasNext?: func -> Bool {
        i < range max-1
    }
   
    next: func -> T {
        i += 1
        i
    }
   
    remove: func -> Bool { false }
}

--
Jeremy Clarke
Twitter: @geckojsc

Amos Wenger

unread,
Nov 13, 2015, 12:10:52 PM11/13/15
to Jeremy Clarke, david.h...@vidhance.com, ooc-lang
rock indeed only checks for the presence of 'iterator' on the type, not if it actually implements the Iterable interface

I think the idea was that for loops should support ranges directly, I'm surprised it doesn't, sounds like something broke (ie. there shouldn't even be a need for RangeIterator).

Is shamanas reading this mailing list?

Jeremy Clarke

unread,
Nov 13, 2015, 12:35:26 PM11/13/15
to Amos Wenger, david.h...@vidhance.com, ooc-lang
Ah yes, I thought I was missing something more obvious here, though range variables would take a bit more work to generate a correct for-loop.

Something like   for (int temp = r.min; temp < r.max; temp++) { ... }   in case the range is modified while looping, but yeah I don't know enough about the compiler internals, maybe you guys intended to do that already?

Also I realised I'm an idiot and should've set  i = range min-1   in my previous code. ^^


Reply all
Reply to author
Forward
0 new messages